Good names should consider their context

With good names for packages, classes, methods, variables,... code should be self-explanatory.  Long method names are not a problem if they really make code read better and don't reveal too much implementation details. Names are more powerful than most developers usually think, they have a profound impact on our designs. In general names should be pronounceable but there are always exceptions.

  • In a small loop, it's OK to name the index i, j, k or something like that you don't have to say theLoopIndexWhatever. In fact, "i" reads better in a short loop.
  • Methods should not contain concrete details, those should be parameters instead:     


          Should better be written like:

                      assertThatThereAre(2, results)

  • Method names should say what they do, but not how:

            addWordIfIsValidAndHasCorrectLength(word,  results)

          Should may be:

                     addValid(word, toResults);

  • The name of the class should be considered when naming methods. The name of the methods should be considered when naming its arguments. Given that methods should not have more than 3 parameters (the less the better), the names of the arguments may be combined with the name of the method, specially if there is a single parameter. Good names care about their context.

            result = expressionResolver.resolveExpression(expression)

          Reads better like this:

                     result = resolver.process(expression)

  • In the case of test methods, the name should describe the behavior without concrete details. The details are inside method body. The test method name is the description and the body is the example:

          Should be:


  • Names should not contain technical details, like the types , because they are an excuse not to search for proper domain names. Modern IDEs provide enough help for the programmer to find out types, code should be business domain oriented.

          Should be:


Avoid prefixes and suffixes like "Abstract*", "I*" (ISomething), "*Impl"...

Don't let the syntactic noise bother you when choosing your names, the fact that there is a brace in the middle should not impede you from writing a line of code that reads like well-written prose 😉

I'll probably will go on updating this post with more examples.


Enjoyed reading this post?
Subscribe to the RSS feed and have all new posts delivered straight to you.