Saturday, February 27, 2010

Selfdocumenting code vs generic names

Some people like their generic names. Every method is named like update() or handleEvent() or init() etc. These names are not very much selfdocumenting. Therefore these methods come with comments very often. The comments explain, what the method does. However, comments are evil, as we all know.

The ideal method does one thing and has a name, which clearly identifies this thing. A proper name helps the reader to understand what it does, without having to read the code. Or at least it gives him a hint about your intentions.

Actually that's another good point. Expressing the intention of the method gives the maintainer the possibility to change the code while keeping the intended functionality.

Sometimes the methodnames are declared by a interface though. In that case you have to use the more generic names. However, inside the method you can call your nicely named methods again. So you still get the benefit from properly naming them.

And don't be afraid of long methodnames. However, try to avoid to use "and" and "or" or something similar to connect disparate things. This is a hint, that the method does more than one thing and probably should be refactored.


  1. Hi Ralf,

    I agree that self-documenting names are best. With the metadata used by some frameworks, you can get the best of both worlds:

    public function fetchNews() : void

    It tells me the news will be fetched at initialization time!

    As for long method names, I usually try to balance descriptiveness with concision. The best method names are both short and self-documenting, though that is easier said than done.


  2. Thanks for your comment Tom.
    The metadata example is a nice one.
    I agree, the names should not be too long.

    My goal with selfdocumenting code is, that it captures the requirements. This is very important for maintenance. The maintainer most likely does not have access to the original story and maybe there are not even tests for this feature. Still the code should tell him, what it's intentions are and not just how to do it, because the how can be wrong or needs to be changed.

  3. Naming is such a delicate area, it's hard to explain. What i was trying to say in my last comment is, if i have the choice between different names, i try to choose the one which represents best my intention and thus the requirements.