Java: static variable declaration best practices

Jawad-Dev :

I have developed a Java Program which contains certain static variables that are used in all the classes.

Now, I want to store those variables at a single platform, which I can refer to call from any class rather than declaring them again & again.

I have researched on the internet and found some good solutions like declaring them in an interface and implementing that interface in my classes.

Also, I can write a separate class and call those variables using the object of that class.

Can anyone suggest the better solution? or which one is better between these two? please explain :)

DevX :

Well to further work on @sleepToken answer there can be multiple ways to what you are looking to do. Again these approaches may depend on the design and at times may totally be different than what is being followed in the code base that you are working on.

For instance in most cases I have seen a convention that constants are defined in an Interface in java and that interface is hardly ever implemented. You can have multiple of these interfaces as well. Like one interface for storing constants related to user and may be another for the constants related to the system

  • IUserConstants.java
  • ISystemConstants.java

Now this is totally up to you to decide the names and what these interfaces will hold. Since these are constants you will define in them they are supposed to be public and static and at times you will make them final as well but make sure that you know the difference between runtime and compile time constants. Again this is something you will have to decide about. Further more public static final are redundant for interfaces. This link just got my attention.

You can check this sample interface

public interface IConstants{
public static final int TIME=10; 
public static final String CONFIG_STRING=SomeClass.LoadValue(); 
}

Another approach I have seen is to use an abstract class that contains all the constants which are static and public and if you want to make sure that it is not further used for implementation you can use a private constructor although I am not sure why this was used because at times legacy code that comes in front hardly makes sense.

public abstract class IConstants
{

  public static final int TIME = 10;
  public static final String CONFIG_STRING = SomeClass.LoadValue();constant

  private IConstants()
  {
    throw new AssertionError();
  }
}

I hope this helps you

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=19094&siteId=1