Home > Technical > Naming Convention taken to another level

Naming Convention taken to another level

February 12th, 2009

Do you think it would it be easier to maintain, understand and increment a code where all the variables that represent the same “thing” are named consistently throughout the code base?

Pat talks about “differences that cause your project death”, I wanted to explore a little bit more one of them: Naming…

Have you ever seen something similar?

PersonalBankAccount account
...
PersonalBankAccount personalAccount
...
PersonalBankAccount bankAccount
...
PersonalBankAccount pAccount
...
PersonalBankAccount pba
...
PersonalBankAccount pbAccount

Different names would help if they add any value to the instance, but the aforementioned examples are a result of different “coding styles” amongst different developers. Some of us like to type, others like to use code completion and it’s dependent on the IDE they are using.

Most of the projects that I’ve worked used checkstyle to enforce code standards. One of the standard checks I’ve always seen is the Naming Convention, which checks identifiers for particular code elements.
If we are following Sun coding conventions, the code below, for example, would generate a checkstyle error

public static final Year minimumYear = new Year(1900); // WRONG
public static final Year MINIMUM_YEAR = new Year(1900); // RIGHT

because a constant should follow the regular expression ^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$

So, code standards are advantageous! Therefore, we can use the same concept to avoid the PersonalBankAccount example.

What I usually do is totally informal, but I try to define with the team an initial convention, Camel Case with all the words for example,

PersonalBankAccount personalBankAccount // wherever possible

Sometimes we need more than one instance in the same block, I like suffixes:

PersonalBankAccount personalBankAccountToTransferMoneyTo
PersonalBankAccount personalBankAccountSourceOfMoney

This is an exception though, wherever possible, use the convention.

But always bear in mind that this is not a rule that you can’t break, it’s just a convention…

I have never seen any tool, or checkstyle check, that could generate something like:

“Number of different instance names for class T”, maybe it’d be interesting… But that’s another, another, another level… :)

Technical ,

  1. February 19th, 2009 at 07:07 | #1

    Uncle Bob has an interesting theory regarding the length of variable names.
    He states that the it should be proportional to the context it is applied.
    So for example if you are defining a variable name inside a method, where you can easily spot its meaning, you can make it small. Otherwise make it meaningful.

  1. No trackbacks yet.