Saturday, October 7, 2017

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

What's in a 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 the truth. And, If code is the best document than names are the 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 that it improves the 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 aspects 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 a 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 developers 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 does not just include best practices but also bad practices to avoid because what not to do is 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 every day we learn something important. So what are we waiting for, let's see a 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 like variable names as abc, temp, data, etc. don't reveal intent; they simply reduce readability. They are best suited for writing test programs, a short demo, and not more than 50 lines of code.

You should never use a 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 the counterpart of the first coding best practice. Instead of pointless names, provide meaningful names, which reveal the intent of the 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 a half point there, but it will not help because best practices are habits and take a 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 than 400 lines long, going back and forth to see definition will only irritate you to refactor that method after some time.


3) Prefer shorter name over longer one if it reveals intent clearly.

I love to use the short name for my methods, but only if it's complete and reveal the 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 the Java bean naming convention like if the variable name is payDate, then getter method name must be getPayDate().

By the way, here I am tossed between jQuery like a 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 the text.


4) Avoid Similar Names

Nothing is worse than similar names; for example, having two variables of employee and employees have every same character except the last one. This kind of difference is 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 that represent the programming concept like List is an ordered collection in Java, so some Java programmer may think that listOfEmployee is an ordered collection of Employee, which if it doesn't, will create misunderstanding.


5) Prefer descriptive name over short form

This is the 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 a shorter name if and only if it reveals intent completely, otherwise choose a longer and descriptive name. What is your method is taking a lot of character, one reason could be that your method is doing more than one thing like loadAndUpdateAllInstrumentRecords(), you can split this into two methods like loadInstruments() and updateInstruments().


6) Follow Java Coding Convention

If you are writing a Java program, then you must follow the 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 conventions are:
        - Start the name of the class as capital letter e.g. Employee, Student or Thread.
        - Start name of method from small character and follow camel case like 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 frameworks use reflection, which works on the bean naming convention. For example display tag uses reflection and bean naming convention to show data in table like if you specify the name, display tag will call getName() method on the table data object.


7) Use Consistent Naming, Avoid Synonyms

This is another naming best practice that 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 like 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 a 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 the 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, the class name should be a noun

Your class name should be a noun and should tell what does this class represent e.g. Employee, Thread, String, etc. Similarly, method names should start with a verb like get, set, do, invoke, etc.

Interface name should describe the ability or CAN DO part like Runnable can run, Callable can be called, etc. package name should follow standard company structure e.g. com.company.project.module.

You can find examples of Java package naming convention in several open-source projects like 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 variables 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 the m_ naming convention, then better stick with it, because it's not possible to rewrite or correct the whole project. It's even worse to have different naming conventions at a different part of code.

Similarly, many programmers use Hungarian notation like bExit for a boolean variable, iMax for integer variables. Those are not too bad if you are working in legacy code, but if you writing it something from scratch don't use them.


11) Avoid using non-ASCII characters and words from the 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 sticks with it. It's not guaranteed that the 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 variables and methods with is, has, and can improve code readability. Methods like isAlive(), hasNext(), canExecute() adds lot of value. You can use the same rule to name boolean variable, which is easy to read when put on a conditional statement like

if(isRaining){
   bringUmbrella();
}


That's all on Java best practice of naming variables, methods, classes, and packages. Most of the advice is 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 aspects 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

6 comments :

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