Java Naming Conventions - Best Practices

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 our day-to-day project work.

Java naming conventions are guidelines that application programmers must follow to produce consistent and readable code throughout the application.

Java Naming Conventions - Best Practices

Table of Contents

  1. Packages Naming Conventions
  2. Classes Naming Conventions
  3. Interfaces Naming Conventions
  4. Methods Naming Conventions
  5. Variables Naming Conventions
  6. Constants Naming Conventions
  7. Abstract Classes Naming Conventions
  8. Exception Classes Naming Conventions
  9. Enumeration Naming Conventions
  10. Generic Types Naming Conventions
  11. Annotations Naming Conventions
  12. Other Naming Conventions

1. Packages Naming Conventions

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, and org.

Example:

package org.springframework.core.convert;
package org.hibernate.criterion;
package org.springframework.boot.actuate.audit;
package org.apache.tools.ant.dispatch;

Oracle Core Packages:

package java.lang;
package java.util;

2. Classes Naming Conventions

Class names should be nouns in UpperCamelCase (mixed case with the first letter of each internal word capitalized). Try to keep your class names simple and descriptive.

Example:

class Employee
class Student
class EmployeeDao
class CompanyService

Oracle Core Packages:

class String
class Color
class Button
class System
class Thread
class Character
class Compiler
class Number

3. Interfaces Naming Conventions

In Java, interface names generally should be adjectives. Interfaces should be in title case with the first letter of each separate word capitalized. In some cases, interfaces can be nouns as well when they represent a family of classes, e.g., List and Map.

Example:

interface Runnable
interface Remote
interface ActionListener
interface Appendable
interface AutoCloseable
interface CharSequence
interface Cloneable
interface Comparable
interface Readable

4. Methods Naming Conventions

Methods should always be verbs. They represent actions, and the method name should clearly state the action they perform. The method name can be a single word or two to three words as needed to clearly represent the action. Words should be in camel case notation.

Example:

public List<Customer> getCustomers();
public void saveCustomer(Customer theCustomer);
public Customer getCustomer(int theId);
public void deleteCustomer(int theId);

More Examples:

getName()
computeTotalWidth()
actionPerformed()
main()
print()
println()

5. Variables Naming Conventions

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

6. Constants Naming Conventions

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

7. Abstract Classes Naming Conventions

The naming convention used for Abstract classes is that the class name must start with the Abstract or Base prefix. This naming convention can vary from organization to organization.

Example:

abstract class AbstractHibernateDao
abstract class AbstractCommonDao
abstract class AbstractBase

Spring Framework Example:

abstract class AbstractBean
abstract class AbstractBeanDefinition
abstract class AbstractUrlBasedView
abstract class AbstractIdentifiable

8. Exception Classes Naming Conventions

The naming convention used for custom Exception classes is that the class name must end with the Exception suffix.

Example:

class TransactionException
class SQLDataException
class ResourceNotFoundException
class ResourceAlreadyExistException

Oracle Core Packages:

class ArithmeticException
class ArrayIndexOutOfBoundsException
class ClassNotFoundException
class CloneNotSupportedException
class EnumConstantNotPresentException
class IllegalAccessException
class IllegalArgumentException
class IllegalMonitorStateException
class IllegalStateException
class IllegalThreadStateException
class IndexOutOfBoundsException

9. Enumeration Naming Conventions

Enum class members should be spelled out in uppercase words, separated by underlines.

Example:

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY
}

10. Generic Types Naming Conventions

Generic type parameter names should be uppercase single letters. The letter T for a type is typically recommended. In JDK classes, E is used for collection elements, S is used for service loaders, and K and V are used for map keys and values.

Example:

public interface Map<K, V> {}
public interface List<E> extends Collection<E> {}
Iterator<E> iterator()

11. Annotations Naming Conventions

Annotation names follow title-case notation. Depending on the requirements, they can be adjectives, verbs, or nouns.

Example:

public @interface FunctionalInterface {}
public @interface Deprecated {}
public @interface Documented {}
public @interface Async {}
public @interface Test {}

12. Specific Naming Conventions (Good to Know)

Apart from the above Java standard naming conventions, there are a few more that are commonly followed in many standard libraries, such as Spring, Apache, Hibernate, etc. Note that these naming conventions can vary between libraries or organizations.

  • Boolean Variables and Methods: Use the is prefix for boolean variables and methods.

    boolean isSet;
    boolean isVisible;
    boolean isFinished;
    boolean isFound;
    boolean isOpen;
    
  • Boolean Setter Methods: Setter methods for boolean variables must have the set prefix.

    void setFound(boolean isFound);
    
  • Alternatives to is: Alternatives such as has, can, and should can fit better in some situations.

    boolean hasLicense();
    boolean canEvaluate();
    boolean shouldAbort = false;
    
  • Compute Methods: Use the term compute in methods where something is computed.

    valueSet.computeAverage();
    matrix.computeInverse();
    
  • Find Methods: Use the term find in methods where something is looked up.

    vertex.findNearestVertex();
    matrix.findSmallestElement();
    node.findShortestPath(Node destinationNode);
    
  • Initialize Methods: Use the term initialize where an object or a concept is established.

    printer.initializeFontSet();
    
  • Plural Form for Collections: Use plural form on names representing a collection of objects.

    Collection<Point> points;
    int[] values;
    
  • Generic Variables: Generic variables should have the same name as their type.

    void setTopic(Topic topic); // NOT: void setTopic(Topic value)
    void connect(Database database); // NOT: void connect(Database db)
    
  • Avoid Redundant Object Names: The name of the object is implicit and should be avoided in a method name.

    line.getLength(); // NOT: line.getLineLength();
    

Conclusion

In this article, we discussed the Java naming conventions for consistent code writing, which makes the code more readable and maintainable. Naming conventions are probably the first best practice to follow while writing clean code in any programming language.

Happy Learning, and Keep Coding!

Comments

Post a Comment

Leave Comment