I am frequently creating methods containing one line of code开发者_Python百科. I do this, as a way of creating self-documenting code, because I can then decide the name of the method, and therefore the behaviour.
On the other hand, creating such methods adds about four lines of code (when I include blank lines).
Question
Is creating one-line methods best practice in any situations? In the case that you think it is: In which situations is it best practice?
your judge should be readability. code lines can be very different in readability, size, complexity and so on. for example, if you have complex line that is not too readable and self-explanatory you can just comment it. but if the same line (or different just by some arguments) are used in more than one place in the code, instead of repeating that comment you wraps in into a method with good name and probably with that comment.
yeah, I know that perfect code doesn't need any comments, but perfect code is just a myth
Aside from readability and maintainability, which should be a given, an important consideration for methods is whether a derived class would need to override this specific method. I tend to do this sparingly, only when I know there will be a need to override behavior in a subclass, because I think too detailed method splitting hampers readability and adds clutter; but of course, the more detailed control a subclass has over what it can override, the more versatile the code.
Using methods summarizes an algorithm as actions. For example instead of counter++
you can use a method: private void incrementCounter() { counter++; }
. So you basically say to you: OK, I first increment the counter, then ..., etc. It is just more human readable. But use what you like in the current situation.
The easier the code is to read, the better! The code should be as self descriptive as possible, and by adding well named functions and variables, you are "most likely" making the code more readable!
精彩评论