Houssam Badri
Houssam Badri

Reputation: 2509

How can be the best way to create constants in Java program?

I have two alternatives:

First: with Singleton design pattern

public class A{
   private static A instance;
   private A(){};
   public A getDefault(){
   if(instance == null)
      instance = new A();
   return instance;
   }
//cst
public static final String cst = "sample";
}

In that way, we get access to cst via A.getDefault().cst

Second: Reference to the class

public class B{
   public static final String cst = "sample";
}

In that way, we get accessed to cst via B.cst, simply.

What is the best way taking into consideration performance (constants for me are numbered and having Image types)?

Upvotes: 2

Views: 1178

Answers (4)

mehdinf
mehdinf

Reputation: 59

Although the simpler is enough, you can add a private constructor. This has two advantages. First, nobody can create an instance of B. Second and more important benefit is that nobody can extent B. Therefore B is just a constant value class in your project.

Upvotes: 1

aioobe
aioobe

Reputation: 421040

The second alternative (a plain public final static field) is simpler and most likely more efficient.

Should you find yourself in need of a more flexible solution, I would advice you to create an enum to hold your values.

public enum MyConstants {
    CST1(new Image("someImage.jpg")),
    CST2(new Image("someOtherImage.jpg"));

    public final Image img;

    private MyConstants(Image img) {
        this.img = img;
    }
}

Note that both the static field and enum solution can be used elegantly with static imports:

import static pkg.B.cst;           // usage:  cst

or

import static pkg.MyConstants.*;   // usage:  CST1  or  CST2

Upvotes: 3

Mureinik
Mureinik

Reputation: 311468

Simpler is better. If it's just a constant, you don't need anything fancier than a straight-forward public static final String cst = "sample";.

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201447

The performance difference is probably unmeasurable. I would prefer the second. You can also use import static like

import static B.cst;

then you can use cst directly. Finally, I recommend you make it all upper-case CST.

Upvotes: 1

Related Questions