Java Standard Naming Conventions

In this article, I would like to explain Java standard naming conventions, which we will follow as the best practices. We should follow these naming conventions in the day to day project work.

Let's discuss package,class,variable,method,constant,abstract class and exception class naming conventions with examples.

Package Name

A package should be named in lowercase characters. There should be only one English word after each dot.
The prefix of a unique package name is always written in all-lowercase ASCII letters and should be one of the top-level domain names, like com, edu, gov, mil, net, org.
Example:
package org.springframework.core.convert;
package org.hibernate.criterion;
package org.springframework.boot.actuate.audit;
package org.apache.tools.ant.dispatch;
Package naming convention used by Oracle for the Java core packages. The initial package name representing the domain name must be in lower case.
package java.lang;
package java.util;

Class Name

Class names should be nouns in UpperCamelCase (in mixed case with the first letter of each internal word capitalized). Try to keep your class names simple and descriptive. Use whole words-avoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML).
Example:
class Employee
class Student
class EmployeeDao
class CompanyService
The class naming convention used by Oracle for the Java core packages.
class String
class Color
class Button
class System
class Thread
class Character
class Compiler
class Number

Interface Name

Interface name should start with an uppercase letter and be an adjective.
Example:
Runnable
Remote
ActionListener
Appendable
AutoCloseable
CharSequence
Cloneable
Comparable
Readable

Method Name

Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized (lowerCamelCase).
Example:
getName()
computeTotalWidth()
actionPerformed()
main()
print()
println(),

Variable Name (Parameter Name, Member Variable, and Local Variable)

The variable name should start with a lowercase letter. Parameter names, member variable names, and local variable names should be written in lowerCamelCase.
Example:
firstName
orderNumber
lastName
phoneNo
id
counter
temp

Constant Variable

Constant variable names should be written in upper characters separated by underscores. These names should be semantically complete and clear.
Example:
RED, YELLOW, MAX_PRIORITY, MAX_STOCK_COUNT

Abstract Class Name

I observed in many standard libraries, the naming conventions used for Abstract class is class name must start with Abstract or Base prefix. This naming convention can vary from organization to organization. 
Example:
AbstractHibernateDao
AbstractCommonDao
AbstractBase
Let's take an example from Spring Framework:
AbstractBean
AbstractBeanDefinition
AbstractUrlBasedView
AbstractIdentifiable

Exception Class Name

I observed in many standard libraries, the naming conventions used for custom Exception Class is class name must end with Exception suffix. 
Example:
TransactionException
SQLDataException
ResourceNotFountException
ResourceAlreadyExistException
The exception class naming convention used by Oracle for the Java core packages.
ArithmeticException
ArrayIndexOutOfBoundsException
ArrayIndexOutOfBoundsException
ClassNotFoundException
CloneNotSupportedException
EnumConstantNotPresentException
Exception
IllegalAccessException
IllegalArgumentException
IllegalMonitorStateException
IllegalStateException
IllegalThreadStateException
IndexOutOfBoundsException

Enum Class Members Name

Enum Class members should be spelled out in upper case words, separated by underlines. Example:
START,RUNNING,STOP,END,MAX_LENGTH,MIN_LENGTH,ERROR_RESPONSE

Specific Naming Conventions(Good to know)

Apart from above java standard naming conventions, there are few more naming conventions would be followed in many standard libraries such as Spring, Apache, Hibernate etc.
Note that these naming conventions can be varied as per different libraries or organizations.
is prefix can be used for boolean variables and methods.
isSet, isVisible, isFinished, isFound, isOpen
This is the naming convention for boolean methods and variables used by Oracle for the Java core packages. 
Using the is prefix solves a common problem of choosing bad boolean names like status or flag. isStatus or isFlag simply doesn't fit, and the programmer is forced to chose more meaningful names.
Setter methods for boolean variables must have set prefix as in:
  void setFound(boolean isFound);
There are a few alternatives to the is a prefix that fits better in some situations. These have, can and should prefixes:
  boolean hasLicense();
  boolean canEvaluate();
  boolean shouldAbort = false;
The term compute can be used in methods where something is computed.
Example:
valueSet.computeAverage();
matrix.computeInverse()
Give the reader the immediate clue that this is a potential time-consuming operation, and if used repeatedly, he might consider caching the result. Consistent use of the term enhances readability.
The term find can be used in methods where something is looked up.
vertex.findNearestVertex();
matrix.findSmallestElement();
node.findShortestPath(Node destinationNode);
Give the reader the immediate clue that this is a simple lookup method with a minimum of computations involved. Consistent use of the term enhances readability.
The term initialize can be used where an object or a concept is established.
printer.initializeFontSet();
The Plural form can be used on names representing a collection of objects.
Collection<Point>  points;
int[]              values;
Enhances readability since the name gives the user an immediate clue of the type of the variable and the operations that can be performed on its elements.
Generic variables should have the same name as their type.
Example:
void setTopic(Topic topic) // NOT: void setTopic(Topic value)
                           // NOT: void setTopic(Topic aTopic)
                           // NOT: void setTopic(Topic t)

void connect(Database database) // NOT: void connect(Database db)
                                // NOT: void connect(Database oracleDB)
The name of the object is implicit and should be avoided in a method name.
Example:
line.getLength();   // NOT: line.getLineLength();
Please write comments, if you want to give any suggestions or feedback about my articles would be appreciated.

If you like my articles and want similar kind of stuff, connect with me on Google +,  FacebookGitHub, and StackOverflow.

Check out our top viewed Java Guides and Java/J2EE Best practices. I hope you like it.

Happy Learning and Keep Coding !!!!.

Recommended Tutorials

Comments

Post a Comment