Software Development

How to write clean code variables

We know how the code we write works, we understand it, we don’t need comments, it’s 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 – it’s 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 Maintainance.

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 is 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 it’s 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. It’s 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 or a Table.

Use words that can be pronounced and avoid abbreviations

There are many common abbreviations that are well known 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. It’s much clearer to say “clientDateOfBirth” than “cDOB” every time 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 interested in finding, should be named using single letters such as i, j and k.

It’s not necessary to use Hungarian Notation or other type encodings

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 it’s 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 exist in physical form. So labeling 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 colloquial and humorous names. Not everyone has the same sense of humor 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 doesn’t help future programmers to understand your code and your code will lose 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 and 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.

Published on Java Code Geeks with permission by Alex Theedom, partner at our JCG program. See the original article here: How to write clean code variables

Opinions expressed by Java Code Geeks contributors are their own.

Alex Theedom

Alex Theedom is a Senior Java Developer and has recently played a pivotal role in the architectural design and development of a microservice based, custom built lottery and instant win game platform. Alex has experience of Java web application development in a diverse range of fields including finance, e-learning, lottery and software development. He is the co-author of Professional Java EE Design Patterns and many articles.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button