We all know methods should be short, and comments can be avoided when methods are short and with meaningful names. But by following these conventions, we sometimes only generate another form of redundant comments. Let me explain it with an example.
if (feeType == FeeType.PERCENTAGE) {
...
}
What's the problem here? It reads not like in human language, or not DSL enough. Let's extract the condition to a one-liner method, and make the method name suitable to be appeared after if.
if (feeIsBasedOnPercentage(feeType)) {
...
}
Much better, right? Now the question is, if the condition needs further explanation, why not explain it directly with a comment side by side, like this.
if (feeType == FeeType.PERCENTAGE) {
// fee is based on percentage
...
}
// fee is based on percentage
...
}
No, this's not good. The comment looks like redundant. It just repeats what's in the if statement. Okay, let's remove the redundant comment.
if (feeType == FeeType.PERCENTAGE) {
...
}
...
}
So, what was the question again?
If you find yourself extract / write
- a very short, usually one-liner, method, and
- it's only called once, and
- method name is repeating what's in the body
private boolean feeIsBasedOnPercentage(FeeType feeType) {
return feeType == FeeType.PERCENTAGE;
}
return feeType == FeeType.PERCENTAGE;
}
Finally, I'd like to guess how this redundant way of programming was developed, just for fun.
private boolean feeIsBasedOnPercentage(FT ft) {
return ft == FT.P;
}
Hope you get the idea of why I call it redundant. If you do, Dependency is the new Inheritance is another one for you.
Disclaimer, code snippets used here are for illustration only.
return ft == FT.P;
}
Hope you get the idea of why I call it redundant. If you do, Dependency is the new Inheritance is another one for you.
Disclaimer, code snippets used here are for illustration only.
No comments:
Post a Comment