Best practices for creating constants in Java

In this blog post I will explain you what are different  and recommend ways of creating constants in Java. As we all know declaring constants is something common in all application.

Lets see standard way of creating constants.

Introduction

Interfaces are adopted widely as constant repositories and it is one of the anti-patterns followed in Java. Such interfaces are called “Constant Interfaces” and do not contain any methods; it consists only fields which are by default public static final.

There are two techniques we could use the constant interfaces in the classes.

  • The interfaces are implemented by the classes where the constants are utilised. Consequently, no need to use the interface name as a prefix to the constant name.
public interface Constants {
  double PI = 3.14;
}

// Class implements the Constant interface
public class Circle implements Constants {
  public double calculateArea(int radius) {
    return PI * radius * radius;
  }
}
  • Directly use the interfaces in the classes without implementing it. As a result, need to use the Interface name prefixed with the constant name. A disadvantage with this approach is classes will be filled with structure {InterfaceName}.{ConstantName}.
public interface Constants {
  double PI = 3.14;
}

public class Circle2 {
  public double calculateArea(int radius) {
    return Constants.PI * radius * radius;
  }
}

As rightly said by Joshua Block in his book Effective Java (2nd edition Item 19 – Use Interfaces only to define types), interfaces should be used only to define types and should not be used for any other purpose.

Solution

Now, to create constants we have several reasonable choices.

  • If the constants are strongly tied to an existing class or interface add them to the class or interface.

Ex: In java.lang.Math,

public static final double E = 2.7182818284590452354;

public static final double PI = 3.14159265358979323846;

  • If we think the constants are the best fit as members of an enumerated type, try using the enum type.
enum Days{
   SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}
  • Otherwise, use a non-instantiable¬†class. Use static import to avoid the use of the class name to prefix every constant name.
public class Constants 
{
  private Constants(){	

  }
  public static final double PI = 3.14;
}


import static com.npn.Constants.*;

public class Circle3 
{
  public double calculateArea(int radius) {
    return PI * radius * radius;
  }
}

References :
https://en.wikipedia.org/wiki/Constant_interface

Manoj Kumar

Manoj Kumar is a technology evangelist and he is currently working as a trainer at NPN Training. He is having 6+ years of experience in companies like Infosys & Mindtree. He has delivered complex projects using technologies like Java, Spring, Hibernate, Micro Services and Hadoop.