04 - Write code once Flashcards
Should you copy code? If not, what would be the alternative?
You should avoid it. Especially with large blocks of code (6+ lines)
Instead, write generic and reusable code.
What is the main argument against copying code?
It causes maintenance issues. Whenever copied code needs to be changed, it needs to be changed in multiple places and it will be hard to keep track of all the duplicates.
When is a block of code a ‘code clone’?
When the code (excluding whitespaces) is exactly the same piece of code as somewhere else in the codebase, which is at least 6 lines long.
What could be an alternative approach to a few classes that contain code clones?
Create a super class that contains the duplicate code and have the few classes extend this super class.
When is copying code ok?
Code with 5 lines or less are considered okay to copy. (Type 2 clone).
Consider this code:
public int methodA() { int foo = 12; if (foo < 10) { return foo + 5; } else { return foo + 2; } } public int methodB() { int foo = 12; if (foo < 10) { return foo + 5; } else { return foo + 2; } }
Should this be refactored?
From a ‘write code once’ perspective, this does not count as a code clone. Therefor, the exam will not expect you to refactor this.