Search code examples
javaspring-ioc

Java Should be a string defined as constant if it being used only at one place


I have a method which uses a String constant as shown below and the value is never used again.

@Service
public class Sample {
    public void test(Greet greet) {
        greet.setInitial("Hi");
    }
}

The value for initial never changes and Sample class is a singleton bean.

My question is for the scenario should we declare a constant as shown below:

@Service
public class Sample {
    private static final String INITIAL="Hi";

    public void test(Greet greet) {
        greet.setInitial(INITIAL)
    }
}

And which approach is better from a performance perspective


Solution

  • It comes down to a case-by-case basis. In this case I'd probably use the String literal greet.setInitial("Hi"); rather than the constant. But it really comes down to how you want to treat or organize this value, for example if you treat the variable as a constant:

    @Service
    public class Sample {
    
        public final int DEFAULT_GREETING = "Hi";
    
        public void test(Greet greet) {
            greet.setInitial(DEFAULT_GREETING);
        }
    }
    

    then you can organize the value at the top of the class despite where it is used in the class, and despite whether it is used once or multiple times, and you can provide access to the constant for outside classes if you want.

    It really comes down to conveying the meaning/use/scope of your value