Saturday, October 7, 2017

10 Programming Best Practices to Name Variables, Methods, Classes and Packages

What's in name? "A rose by any other name would smell as sweet" is a famous quote from William Shakespeare's classic Romeo and Juliet, but sorry to say, name matter a lot in programming and coding.  It's also said that code is the best document for any software, because any other document or comments can become outdated quickly, but code will always tell you truth; If code is then best document than names are most critical element of it. Every effort, small or big, invested while naming variables or methods, pays in both short term and long term. In fact, if you ask me just one coding practice to follow, It would definitely recommend giving meaningful names to your variables and methods. One reason, I push for this coding practice is because it improves readability of any algorithm or program drastically. Since every programmer spends more time reading code than writing, It would make a lot of sense to give meaningful names to your programming element. Readability is also one of the most important aspect of clean code. If you happen to read Clean code, the book by Uncle Bob, you would have seen a whole chapter on meaningful names, this just shows how important it is to name your variable, methods, classes and packages properly. Though these programming best practices are given from a Java programmer's perspective, they are equally useful in any other programming language. In fact, most of them are independent of any programming language and can be used while writing bash script, SQL stored procedures, C++ code and any other computer program. In fact you will value these practices more in case of shell script and database stored procedure because they don't have tools as smart as Java IDEs.

Java Best Practices of Proper Naming Convention

Here are some of the programming or coding best practices professional Java developer follow while writing code, including myself. Most of these practices are common sense and acquired via years of experience of reading and writing code.

It not just include best practices but also bad practices to avoid, because what not to do are equally important as what to do. At the same time, this list is by no means complete and if you have any other good practice while naming programming elements, feel free to share.

Perfection is a journey and everyday we learn something important. So what are we waiting for, let's see better way to name your variables, methods, classes and packages in a computer program.

Programming Best For Naming Variables Methods and Packages

1) Avoid Pointless Names
Pointless names e.g. variable names as abc, temp, data etc doesn't reveal intent, they simply reduce readability. They are best suited for writing test programs, short demo and not more than 50 lines of code. You should never use pointless name in your routines in a professional project. Why? because test programs are not maintained but a real project is maintained for years, only you work on test programs but many developers work in a professional project.

2) Give Meaningful Names
This is counterpart of first coding best practice. Instead of pointless names, provide meaningful names, which reveals intent of programmer. For example method name with getPayDate() is much better with gpd() or getPD() because if I read getPayDate() somewhere in my code, I would know that this method is going to return me pay date, even after several years, but same cannot be said for gpd() or getPD().  One programmer was arguing with me that he will not follow this principle with private methods because private methods are only accessible in the class and anyone can see their definition. He might have half point there but it will not help, because best practices are habits and takes long time to develop. If you don't follow them always, you are more like will not follow even when you need them. Also if your class is more that 400 lines long, going back and forth to see definition will only irritate you to re-factor that method after some time.

3) Prefer shorter name over longer one, if it reveal intent clearly.
I love to use short name for my methods but only if it's complete and reveal programmer's intention clearly, for example between getPayDate() and retreivePaymentDate(), former is better than later. Since both are able to reveal purpose, shorter ones are easy to read and write, but don't forget to follow Java bean naming convention e.g. if variable name is payDate then getter method name must be getPayDate(). By the way here I am tossed between jQuery like method than Java's bean convention. I really enjoyed using methods like text() which return text (without argument)  and overloaded version text(data) (with argument) which changes text.

4) Avoid Similar Names
Nothing is worse than similar names, for example having two variables employee and employees, has every same character except last one. This kind of differences are very hard to spot, and often leads to subtle bugs, which are even harder to find during code reviews. If you have to represent a collection or plural, prefer something like listOfEmployees, bunchOfEmployees over employees. By the way, be careful while using names which represent programming concept e.g. List is a ordered collection in Java, so some Java programmer may think that listOfEmployee is a ordered collection of Employee, which if it doesn't, will create misunderstanding.

5) Prefer descriptive name over short form
This is counterpart of our earlier Java naming best practices, where I had argued for shorter names. Disclaimer there was that, shorter name must reveal purpose of variable or method e.g. getPayDate() is fine, but getLInd() is not as good as getLiquidityIndicator(). So prefer shorter name if and only if it reveal intent completely, otherwise choose longer and descriptive name. What is your method is taking lot of character, one reason could be that your method is doing more than one thing e.g. loadAndUpdateAllInstrumentRecords(), you can split this into two methods e.g. loadInstruments() and updateInstruments().

6) Follow Java Coding Convention
If you are writing Java program, then you must follow Java Coding Convention, It's even more important if you are writing open source code. Since Java Coding Conventions are quite common among Java developers, it makes it easy for another programmer to read your code. Some of the most common Java coding convention are:
        - Start name of class as capital letter e.g. Employee, Student or Thread.
        - Start name of method from small character and follow camel case e.g. getEmployee(), getPayDate() etc.
        - Use camel case in variable names as well e.g. price, quantity, totalAmount etc.
        - Use all caps for constants in Java e.g. MAX_QUANTITY, MAX_PRICE etc.
        - follow bean naming convention, because many open source framework use reflection, which works on bean naming convention. For example display tag uses reflection and bean naming convention to show data in table e.g. if you specify name, display tag will call getName() method on table data object.

7) Use Consistent Naming, Avoid Synonyms
This is another naming best practice which can be argued, but consistency overrules any potential argument. Having synonyms for similar methods doesn't harm too much, but it's better to be consistent e.g. instead of having three different methods destroy(), kill(), or finish() at different modules, prefer one of them e.g. destroy(). This will make your API more usable, as programmer will be able to predict and search more easily. It also helps you to keep one functionality at one place and avoid accidental duplication of code, remember DRY (Don't Repeat Yourself).

8) Follow Classical Programming Convention
In first Java best practices of  naming variables, I had said that avoid using pointless names, but there are exceptions e.g. i and j as loop counter in for loop, as shown below.
for(int i=0; i<10; i++){
  // your code
Programmers are so familiar with that, they would be surprised to see any other name for loop counters. Similarly getters and setters are named like that.

9) In Java, class name should be noun
Your class name should be noun and should tell what does this class represent e.g. Employee, Thread, String etc. Similarly method names should start with verb e.g. get, set, do, invoke etc. Interface name should describe ability or CAN DO part e.g. Runnable can run, Callable can be called etc. package name should follow standard company structure e.g. You can find examples of Java package naming convention in several open source project e.g. Apache Commons BeanUtils uses org.apache.commons.beanutils.BasicDynaBean.

10) Avoid Clutters like _, m_, o_
Some programmers tend to use specifies like m_ to denote member variables, or simply _ (underscore) to differentiate member variable with local variables. Avoid doing that because, it looks like clutter. Instead of this you better choose meaningful and unique names. By the way, if your project already uses m_ naming convention, then better stick with it, because it's not possible to rewrite or correct whole project. It's even worse to have different naming convention at different part of code. Similarly, many programmer uses Hungarian notation e.g. bExit for boolean variable, iMax for integer variables. Those are not too bad, if you are working in a legacy code, but if you writing it something from scratch don't use them.

11) Avoid using non ASCII characters and words from local language
Using any character other than ASCII character, especially non English is worst practice. Never use characters from other languages, it might not be supported on all platforms, IDE and different machines. Similarly, don't use words from local languages e.g. Hindi, French or German. English is a universal language for programming and stick with it. It's not guaranteed that next programmer, who will maintain your code, will understand local languages, so better avoid it.

12) Make good use of common verb e.g. is, has, can or do
I found naming boolean variable and methods with is, has, and can improves code readability. Methods like isAlive(), hasNext(), canExecute() adds lot of value. You can use same rule to name boolean variable, which are easy to read when put on conditional statement e.g.

That's all on Java best practice of naming variables, methods, classes and packages. Most of advice are independent of programming construct and can be used, while writing bash scripts, routines, or SQL stored procedures. Though naming conventions are one of the fundamental aspect of programming, it's often overlooked. Don't satisfy with first go, always try to read your code and strive for more meaningful names, which are clear and reveal intent. Also nothing is as bad as inconsistency, don't mix upper and lower case, Hungarian convention to Java code convention etc. Let us know, what best practices you guys are following while naming variables and methods in Java.

Do you like Best Practices articles? If Yes, then here are some amazing posts for further reading and learning more techniques
SOLID Principles of Object Oriented Design
From 0 to 1: Design Patterns - 24 That Matter - In Java
Clean Code: Writing Code for Humans
Exception Handling Practices for Java Programmer
Tired with Null, follow these practices to avoid NPE in Java
Clean Code and Clean Coder book by Uncle Bob
Effective Java by Josh Bloch


Anonymous said...

Hungarian notation has proven to be missleading in case you change variable type (you will need to rename the variable too). We have IDEs at hand to check variable type, it's not needed to be hardcoded in the name.

Anonymous said...

Great article. I can only recommend those who are reading this grab a copy of "Clean Code". You will learn a lot.

Anonymous said...

In point 10 you contradict your first statement "Readability is also one of the most important aspect of clean code". Why would you not use specific notation to mark memeber variables or types of variables? I know you can just look them up, but that takes time. Even if it takes a second, thats a second saved by seeing that bExit is a boolean.

javin paul said...

@Anonymous first, Indeed "Clean Code" is one of the must read Programming book. Every developer must read it sooner than later.

javin paul said...

@Anonymous 3rd, Hungarian notation is not a right way to improve readability, there was time when it was useful but in today's age of modern IDE, I don't see any point of using this. If you look at first comment by another @Anonymous, he has good point why you should not use Hungarian notation in Java today.

Anonymous said...

Please do not start with hungarian notation, Java's own naming convention like get, set, is, has are pretty decent and you should stick with it. Since they are standard, tools can automatically generate codes and all, once you moved out of standar, you will leave with your own. I know several tools exists which creates Java classes from XML XSD files e.g. Apache XMLBeans, if there was no standard, development of such tool was impossible. Bottom line is follow Java's variable, method and class naming convention and you will be good with your best practices.

Post a Comment