Hot Posts

Clean Code: Variables

We know how the code we write works, we understand it, we don’t need comments, its obvious, of course, we wrote it. This is what we all think and its true – well today its true, but tomorrow, next week, next year – its not likely to be so true. And do others understand the way you code? Is the code obvious to the new team member that must maintain your code. Will you be spending hours explain something that should be obvious or fixing errors made by others because they didn’t understand your ‘obvious’ code?

We hope that this situation never occurs but it does. This why clean code it so important. Making your code as clean as possible will improve its quality so that others will understand it intuitively, reducing the possibility of errors and improving the quality of maintained.

In this article I will talk about only one aspect of clean code, variables. It is structured in short paragraphs under topical headings.

Use intention revealing name

The variable name should reveal the intention of the programmer. It should be obvious what the programmer intended that the variable be used for. Don’t refer to an object that models an employee using the variable name e. Call it what it is: an employee. Likewise when referring to values such as integers use intention revealing name for example: use int highestScore instead of int i.

Use methods instead of static variables to test state

It is more intuitive to call a method to find out the state of a system rather query an array using statically defined variables.

For example use connection.isAlive instead of connections[STATUS] = ALIVE where connection is an object representing the connection, it has a method isAlive() that returns the connection status and connections[] is an array that contains the status of the connection. ALIVE is the status value of a live connection.

Avoid names that are misleading or potentially confusing

Be kind to those will maintain your code and never use the variable’s type in the variable’s name. If accountList is a list then don’t use the word list in the variables name.  Confusion may be caused as its possible that the variable type changes from a list to an object of a different type.

The same can be said of name that are very long, similar to other variables or synonyms. Its easy to become confused between staff and employee. Which variable do I use? The meaning of staff and employee is the same. What’s the difference between message and aMessage or cashAmount and liquidAmount. Avoid similar sounding names. 

Make the variable name IDE auto-complete friendly

Most developers use auto complete IDE tools so will choose the variable or method based on its name.

  • Write code for programmers not for compilers. Using the word clazz because class is a reserved word is not acceptable
  • Use names such as source and destination instead of a1 and a2
  • Avoid using noise words such as String, Data, List, Object, Table, Variable. They don’t add anything to the value of the name and may confuse if what is name StringTable is neither a String nor a Table.

Use words that can be pronounced and avoid abbreviations.

There are many common abbreviation that are well know by everyone, but many that are not. Avoid using any abbreviations, for example its better to use clientDateOfBirth rather that cDOB. Imagine that you must talk about your code in a meeting with people who are not familiar with what your code does. Its much clearer to say “clientDateOfBirth” than “cDOB” everytime you want to refer to that variable.

Make the variable searchable.

There are times where you need to use the IDE’s search facility to find a variable. If you assume that the variable has a name related to its function it is much easier to find. So this means ensuring that you spell it correctly, avoid single letter variables and name it sensibly.

However variables that are used for loops, that you are not interest in finding, should be named using single letter such as i, j and k.

Its not necessary to use Hungarian Notation or other type encoding

It is no longer necessary to use the Hungarian Notation as the IDE enforces types thus most errors are detected before compile type and it makes it easier to change the type of the variable if the name does not include the type. For example: we have the  variable: String phoneNumberInt and the variable type has changed to String but the variable name implies that its an int.

Encode the implementation of the interface

If the interface name is Person then the implementation would be PersonImp.

Class and Object names should be nouns or noun phrases

It makes sense to name an object using a noun. Objects are designed to represent things that we want to model. Often, things that exit in physical form. So labelling a class Account, Person, Company, ShoppingBasket or Wiki makes logical sense. Also it makes the name searchable.

Methods should be verb or verb phrase

Methods do things so naming them using a verb is logical. Name methods like save(), sendMessage(), convert() and newPage() will make the code more intuitive. Follow the java bean convention of prefixing mutator/accessor methods with get, set and is.

Develop consistent name conversions

If you use get don’t then use fetch, retrieve or obtain unless you are naming a method whose semantics relate to a different concept. Be consistent in the names given to methods in different classes for example, if you name a class email don’t then use mail, eMail, electronicMail to name other classes.

Avoid coloquail and humorous names. Not everyone has the same sense of humour or watches the same TV shows o films. Naming a method showMeTheMoney() rather than getBalance() is only funny the first time and only if you saw the film and liked it. It doen’t help future programmers to understand your code and your code will loose credibility when reviewed by others.

Use one word for each concept and don’t use the same word just for consistency. For example, use add when you sum two values together but don’t use it when adding a new record to a database, using insert separates the concepts and use concatenate when joining Strings. Keep the concept separate by using different names.

Use technical names. Your code will be read by programmers not laypersons, so go ahead an use words like listener, visitor, view, model, controller etc.

Variables that are logically connected such as an address or personal data can be prefixed. For example, firstName, lastName, telephonNumber, maritalStatus, state and country can be prefixed to clarify that they belong together: personFirstName, personState etc. this clearifies that state refers to the state in which the person lives.

Conclusion

Variables names are just a small part of making your code clean but it goes a long way to ensuring that those who maintain your code  understand it is the way that it was intended to be understood.

2 Comments on Clean Code: Variables

  1. Remember conditions are variables too, when you don’t define them you can’t encode your intent into their names, don’t do this: if ($person->age > 18) {} do something like this: $is_legal_adult = $person->age > 18; if ($is_legal_adult) {}

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: