Where to declare Constants in Java

Its been an topic of debate where should constants be declared. Let look at approaches :-
  1. Declared in an Interface.
  2. Declared in a Class.
  3. Enums
Going through google, i found number of explanation for both of these. Each have their pros and cons. I'll try to summarise and share my thoughts on it.

Lets start with interface. In Java, Interfaces are used as abstract type, that contain method signatures, constants and nested types as according to Oracle. We can use interfaces to defined a contract or for communication  as explained in my previous article. If we define constants here, we can have the following consequences:-
  1. We cannot stop a class to not implement an interface.So a Global constant interface can be used for subtype which is not advisable.
  2. We cannot give define constants depend on certain state condition.
  3. All the constants would stay in memory all the time.
Although, we can define constants in interfaces, we have the above constraints. Lets look how we overcome all of this in Class.

We can declare a UtilConstant class. Make it final and make the constructor private. With this, we can overcome the problem (1) of interfaces.
Also if constants to be declared need some computation or a function call, we can do in class as defined below:-
public class constantClassExample {
static final int BATCH_SIZE=getBatchsize();

   private static int getBatchsize() {
   // User defined computation
   return 0;
  }
}
So we have seen that we can define constants at runtime i.e (2). 
So to overcome (3) problem in interfaces, we can make use of static imports. It allows you to import one or two members as per requirement. Be aware, if you import all the constants using '*' , it can polluter your class space.
Afcourse, if the constants are relevent to current class, it will help keeping the code encapsulated.

Last comes the Enums. If the constants can be clubbed to one single type or we need to enumerate , we can use Enums.

For futher readings -

Comments

  1. This comment has been removed by the author.

    ReplyDelete
  2. I think constants in the interfaces are very poor design factor because was designed to define a CONTRACT and not to be a synthetic sugar.
    Constants in interfaces are generally very bad idea from the clean code point of view.

    So, if you need to put it "somewhere" try to put it in the business class or better create a new ENUM (which is created for such purposes).

    my 5 cents :)

    cheers
    Albert

    ReplyDelete
  3. this is a good article..

    ReplyDelete

Post a Comment

Popular posts from this blog

When to use getClass() and instanceOf in Java

How class.forName loads the Database Driver in JDBC

Why Time gets truncated with ResutSet getDate() function.