04 - Write code once Flashcards

1
Q

Should you copy code? If not, what would be the alternative?

A

You should avoid it. Especially with large blocks of code (6+ lines)
Instead, write generic and reusable code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the main argument against copying code?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

When is a block of code a ‘code clone’?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What could be an alternative approach to a few classes that contain code clones?

A

Create a super class that contains the duplicate code and have the few classes extend this super class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

When is copying code ok?

A

Code with 5 lines or less are considered okay to copy. (Type 2 clone).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

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?

A

From a ‘write code once’ perspective, this does not count as a code clone. Therefor, the exam will not expect you to refactor this.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly