How do you define a class of constants in Java?

后端 未结 10 2014
终归单人心
终归单人心 2020-12-07 12:44

Suppose you need to define a class which all it does is hold constants.

public static final String SOME_CONST = \"SOME_VALUE\";

What is the

相关标签:
10条回答
  • 2020-12-07 13:28
    1. One of the disadvantage of private constructor is the exists of method could never be tested.

    2. Enum by the nature concept good to apply in specific domain type, apply it to decentralized constants looks not good enough

    The concept of Enum is "Enumerations are sets of closely related items".

    1. Extend/implement a constant interface is a bad practice, it is hard to think about requirement to extend a immutable constant instead of referring to it directly.

    2. If apply quality tool like SonarSource, there are rules force developer to drop constant interface, this is a awkward thing as a lot of projects enjoy the constant interface and rarely to see "extend" things happen on constant interfaces

    0 讨论(0)
  • 2020-12-07 13:29

    Use a final class. for simplicity you may then use a static import to reuse your values in another class

    public final class MyValues {
      public static final String VALUE1 = "foo";
      public static final String VALUE2 = "bar";
    }
    

    in another class :

    import static MyValues.*
    //...
    
    if(variable.equals(VALUE1)){
    //...
    }
    
    0 讨论(0)
  • 2020-12-07 13:31

    enums are fine. IIRC, one item in effective Java (2nd Ed) has enum constants enumerating standard options implementing a [Java keyword] interface for any value.

    My preference is to use a [Java keyword] interface over a final class for constants. You implicitly get the public static final. Some people will argue that an interface allows bad programmers to implement it, but bad programmers are going to write code that sucks no matter what you do.

    Which looks better?

    public final class SomeStuff {
         private SomeStuff() {
             throw new Error();
         }
         public static final String SOME_CONST = "Some value or another, I don't know.";
    }
    

    Or:

    public interface SomeStuff {
         String SOME_CONST = "Some value or another, I don't know.";
    }
    
    0 讨论(0)
  • 2020-12-07 13:32

    Or 4. Put them in the class that contains the logic that uses the constants the most

    ... sorry, couldn't resist ;-)

    0 讨论(0)
提交回复
热议问题