javalogo

Three Java Pet Peeves

Types in Variable and Method Names

   List<Name> nameList = new ArrayList<>();

Why not just call that list “names?” I know its a list. Java is a strongly-typed language. We’re not going to be able to accidentally assign another value to it. And now I have to write “nameList” all over the place. Also, what if in the future I decide I need to store the names in a map, set, or other collection? Then I would have to refactor all code that refers to it.

This pet peeve really gets bad for me when something like this happens:

   public Collection<Name> getNameList() {
      // hopefully you get the idea - DON'T PUT THE TYPE OF THE SPECIFIC CLASS GET IN YOUR METHOD NAME!
   }

In this example the method signature enforces the type as a “Collection” (coding to interface = good!) but the “getNameList()” suggests that a more specific type (“List”) is being used (violates encapsulation – bad!).

Deprecating Without Documenting

   @Deprecated
   public boolean reticulateSplines() {
      // code elided

Nooo!! If this method does exactly what I want to do, but it is deprecated, then I need to know what I should use instead! Java even provides a special annotation for Javadoc so that you can document why it is deprecated and which preferred method to use instead. Do that!

Similar but Different Naming

Perhaps the worst one:

    Transaction t = getTransactionFromEvent(ev);
    TransactionEvent e = getTransactionEventFromTransaction(t);
    TransactionSubEvent se = getSubEventFromEvent(e);
    Map<Transaction, Map<TransactionEvent, TransactionSubEvent>> transactionToEventMap = //...you get the idea

If you want your code to have bugs there is no better way than to use vague variable names and have a whole set of variables and methods named in a similar vague manner! Try to be very explicit with variable names and I’ll thank you for it!

Leave a Reply

Your email address will not be published. Required fields are marked *