What is the best way to implement constants in Java?

Viewed 845499

I've seen examples like this:

public class MaxSeconds {
   public static final int MAX_SECONDS = 25;
}

and supposed that I could have a Constants class to wrap constants in, declaring them static final. I know practically no Java at all and am wondering if this is the best way to create constants.

28 Answers

That is perfectly acceptable, probably even the standard.

(public/private) static final TYPE NAME = VALUE;

where TYPE is the type, NAME is the name in all caps with underscores for spaces, and VALUE is the constant value;

I highly recommend NOT putting your constants in their own classes or interfaces.

As a side note: Variables that are declared final and are mutable can still be changed; however, the variable can never point at a different object.

For example:

public static final Point ORIGIN = new Point(0,0);

public static void main(String[] args){

    ORIGIN.x = 3;

}

That is legal and ORIGIN would then be a point at (3, 0).

I would highly advise against having a single constants class. It may seem a good idea at the time, but when developers refuse to document constants and the class grows to encompass upwards of 500 constants which are all not related to each other at all (being related to entirely different aspects of the application), this generally turns into the constants file being completely unreadable. Instead:

  • If you have access to Java 5+, use enums to define your specific constants for an application area. All parts of the application area should refer to enums, not constant values, for these constants. You may declare an enum similar to how you declare a class. Enums are perhaps the most (and, arguably, only) useful feature of Java 5+.
  • If you have constants that are only valid to a particular class or one of its subclasses, declare them as either protected or public and place them on the top class in the hierarchy. This way, the subclasses can access these constant values (and if other classes access them via public, the constants aren't only valid to a particular class...which means that the external classes using this constant may be too tightly coupled to the class containing the constant)
  • If you have an interface with behavior defined, but returned values or argument values should be particular, it is perfectly acceptible to define constants on that interface so that other implementors will have access to them. However, avoid creating an interface just to hold constants: it can become just as bad as a class created just to hold constants.

It is a BAD PRACTICE to use interfaces just to hold constants (named constant interface pattern by Josh Bloch). Here's what Josh advises:

If the constants are strongly tied to an existing class or interface, you should add them to the class or interface. For example, all of the boxed numerical primitive classes, such as Integer and Double, export MIN_VALUE and MAX_VALUE constants. If the constants are best viewed as members of an enumerated type, you should export them with an enum type. Otherwise, you should export the constants with a noninstantiable utility class.

Example:

// Constant utility class
package com.effectivejava.science;
public class PhysicalConstants {
    private PhysicalConstants() { }  // Prevents instantiation

    public static final double AVOGADROS_NUMBER   = 6.02214199e23;
    public static final double BOLTZMANN_CONSTANT = 1.3806503e-23;
    public static final double ELECTRON_MASS      = 9.10938188e-31;
}

About the naming convention:

By convention, such fields have names consisting of capital letters, with words separated by underscores. It is critical that these fields contain either primitive values or references to immutable objects.

In Effective Java (2nd edition), it's recommended that you use enums instead of static ints for constants.

There's a good writeup on enums in Java here: http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html

Note that at the end of that article the question posed is:

So when should you use enums?

With an answer of:

Any time you need a fixed set of constants

Just avoid using an interface:

public interface MyConstants {
    String CONSTANT_ONE = "foo";
}

public class NeddsConstant implements MyConstants {

}

It is tempting, but violates encapsulation and blurs the distinction of class definitions.

Creating static final constants in a separate class can get you into trouble. The Java compiler will actually optimize this and place the actual value of the constant into any class that references it.

If you later change the 'Constants' class and you don't do a hard re-compile on other classes that reference that class, you will wind up with a combination of old and new values being used.

Instead of thinking of these as constants, think of them as configuration parameters and create a class to manage them. Have the values be non-final, and even consider using getters. In the future, as you determine that some of these parameters actually should be configurable by the user or administrator, it will be much easier to do.

The number one mistake you can make is creating a globally accessible class called with a generic name, like Constants. This simply gets littered with garbage and you lose all ability to figure out what portion of your system uses these constants.

Instead, constants should go into the class which "owns" them. Do you have a constant called TIMEOUT? It should probably go into your Communications() or Connection() class. MAX_BAD_LOGINS_PER_HOUR? Goes into User(). And so on and so forth.

The other possible use is Java .properties files when "constants" can be defined at run-time, but not easily user changeable. You can package these up in your .jars and reference them with the Class resourceLoader.

That's the right way to go.

Generally constants are not kept in separate "Constants" classes because they're not discoverable. If the constant is relevant to the current class, keeping them there helps the next developer.

I agree that using an interface is not the way to go. Avoiding this pattern even has its own item (#18) in Bloch's Effective Java.

An argument Bloch makes against the constant interface pattern is that use of constants is an implementation detail, but implementing an interface to use them exposes that implementation detail in your exported API.

The public|private static final TYPE NAME = VALUE; pattern is a good way of declaring a constant. Personally, I think it's better to avoid making a separate class to house all of your constants, but I've never seen a reason not to do this, other than personal preference and style.

If your constants can be well-modeled as an enumeration, consider the enum structure available in 1.5 or later.

If you're using a version earlier than 1.5, you can still pull off typesafe enumerations by using normal Java classes. (See this site for more on that).

I prefer to use getters rather than constants. Those getters might return constant values, e.g. public int getMaxConnections() {return 10;}, but anything that needs the constant will go through a getter.

One benefit is that if your program outgrows the constant--you find that it needs to be configurable--you can just change how the getter returns the constant.

The other benefit is that in order to modify the constant you don't have to recompile everything that uses it. When you reference a static final field, the value of that constant is compiled into any bytecode that references it.

A good object oriented design should not need many publicly available constants. Most constants should be encapsulated in the class that needs them to do its job.

A Constant, of any type, can be declared by creating an immutable property that within a class (that is a member variable with the final modifier). Typically the static and public modifiers are also provided.

public class OfficePrinter {
    public static final String STATE = "Ready";  
}

There are numerous applications where a constant's value indicates a selection from an n-tuple (e.g. enumeration) of choices. In our example, we can choose to define an Enumerated Type that will restrict the possible assigned values (i.e. improved type-safety):

public class OfficePrinter {
    public enum PrinterState { Ready, PCLoadLetter, OutOfToner, Offline };
    public static final PrinterState STATE = PrinterState.Ready;
}

A single, generic constants class is a bad idea. Constants should be grouped together with the class they're most logically related to.

Rather than using variables of any kind (especially enums), I would suggest that you use methods. Create a method with the same name as the variable and have it return the value you assigned to the variable. Now delete the variable and replace all references to it with calls to the method you just created. If you feel that the constant is generic enough that you shouldn't have to create an instance of the class just to use it, then make the constant method a class method.

FWIW, a timeout in seconds value should probably be a configuration setting (read in from a properties file or through injection as in Spring) and not a constant.

What is the difference

1.

public interface MyGlobalConstants {
    public static final int TIMEOUT_IN_SECS = 25;
}

2.

public class MyGlobalConstants {
    private MyGlobalConstants () {} // Prevents instantiation
    public static final int TIMEOUT_IN_SECS = 25;
}

and using MyGlobalConstants.TIMEOUT_IN_SECS wherever we need this constant. I think both are same.

I wouldn't call the class the same (aside from casing) as the constant ... I would have at a minimum one class of "Settings", or "Values", or "Constants", where all the constants would live. If I have a large number of them, I'd group them up in logical constant classes (UserSettings, AppSettings, etc.)

To take it a step further, you can place globally used constants in an interface so they can be used system wide. E.g.

public interface MyGlobalConstants {
    public static final int TIMEOUT_IN_SECS = 25;
}

But don't then implement it. Just refer to them directly in code via the fully qualified classname.

For Constants, Enum is a better choice IMHO. Here is an example

public class myClass {

public enum myEnum {
    Option1("String1", 2), 
    Option2("String2", 2) 
    ;
    String str;
            int i;

            myEnum(String str1, int i1) { this.str = str1 ; this.i1 = i }


}

One of the way I do it is by creating a 'Global' class with the constant values and do a static import in the classes that need access to the constant.

It is BAD habit and terribly ANNOYING practice to quote Joshua Bloch without understanding the basic ground-zero fundamentalism.

I have not read anything Joshua Bloch, so either

  • he is a terrible programmer
  • or the people so far whom I find quoting him (Joshua is the name of a boy I presume) are simply using his material as religious scripts to justify their software religious indulgences.

As in Bible fundamentalism all the biblical laws can be summed up by

  • Love the Fundamental Identity with all your heart and all your mind
  • Love your neighbour as yourself

and so similarly software engineering fundamentalism can be summed up by

  • devote yourself to the ground-zero fundamentals with all your programming might and mind
  • and devote towards the excellence of your fellow-programmers as you would for yourself.

Also, among biblical fundamentalist circles a strong and reasonable corollary is drawn

  • First love yourself. Because if you don't love yourself much, then the concept "love your neighbour as yourself" doesn't carry much weight, since "how much you love yourself" is the datum line above which you would love others.

Similarly, if you do not respect yourself as a programmer and just accept the pronouncements and prophecies of some programming guru-nath WITHOUT questioning the fundamentals, your quotations and reliance on Joshua Bloch (and the like) is meaningless. And therefore, you would actually have no respect for your fellow-programmers.

The fundamental laws of software programming

  • laziness is the virtue of a good programmer
  • you are to make your programming life as easy, as lazy and therefore as effective as possible
  • you are to make the consequences and entrails of your programming as easy, as lazy and therefore as effective as possible for your neigbour-programmers who work with you and pick up your programming entrails.

Interface-pattern constants is a bad habit ???

Under what laws of fundamentally effective and responsible programming does this religious edict fall into ?

Just read the wikipedia article on interface-pattern constants (https://en.wikipedia.org/wiki/Constant_interface), and the silly excuses it states against interface-pattern constants.

  • Whatif-No IDE? Who on earth as a software programmer would not use an IDE? Most of us are programmers who prefer not to have to prove having macho aescetic survivalisticism thro avoiding the use of an IDE.

    • Also - wait a second proponents of micro-functional programming as a means of not needing an IDE. Wait till you read my explanation on data-model normalization.
  • Pollutes the namespace with variables not used within the current scope? It could be proponents of this opinion

    • are not aware of, and the need for, data-model normalization
  • Using interfaces for enforcing constants is an abuse of interfaces. Proponents of such have a bad habit of

    • not seeing that "constants" must be treated as contract. And interfaces are used for enforcing or projecting compliance to a contract.
  • It is difficult if not impossible to convert interfaces into implemented classes in the future. Hah .... hmmm ... ???

    • Why would you want to engage in such pattern of programming as your persistent livelihood? IOW, why devote yourself to such an AMBIVALENT and bad programming habit ?

Whatever the excuses, there is NO VALID EXCUSE when it comes to FUNDAMENTALLY EFFECTIVE software engineering to delegitimize or generally discourage the use of interface constants.

It doesn't matter what the original intents and mental states of the founding fathers who crafted the United States Constitution were. We could debate the original intents of the founding fathers but all I care is the written statements of the US Constitution. And it is the responsibility of every US citizen to exploit the written literary-fundamentalism, not the unwritten founding-intents, of the US Constitution.

Similarly, I do not care what the "original" intents of the founders of the Java platform and programming language had for the interface. What I care are the effective features the Java specification provides, and I intend to exploit those features to the fullest to help me fulfill the fundamental laws of responsible software programming. I don't care if I am perceived to "violate the intention for interfaces". I don't care what Gosling or someone Bloch says about the "proper way to use Java", unless what they say does not violate my need to EFFECTIVE fulfilling fundamentals.

The Fundamental is Data-Model Normalization

It doesn't matter how your data-model is hosted or transmitted. Whether you use interfaces or enums or whatevernots, relational or no-SQL, if you don't understand the need and process of data-model normalization.

We must first define and normalize the data-model of a set of processes. And when we have a coherent data-model, ONLY then can we use the process flow of its components to define the functional behaviour and process blocks a field or realm of applications. And only then can we define the API of each functional process.

Even the facets of data normalization as proposed by EF Codd is now severely challenged and severely-challenged. e.g. his statement on 1NF has been criticized as ambiguous, misaligned and over-simplified, as is the rest of his statements especially in the advent of modern data services, repo-technology and transmission. IMO, the EF Codd statements should be completely ditched and new set of more mathematically plausible statements be designed.

A glaring flaw of EF Codd's and the cause of its misalignment to effective human comprehension is his belief that humanly perceivable multi-dimensional, mutable-dimension data can be efficiently perceived thro a set of piecemeal 2-dimensional mappings.

The Fundamentals of Data Normalization

What EF Codd failed to express.

Within each coherent data-model, these are the sequential graduated order of data-model coherence to achieve.

  1. The Unity and Identity of data instances.
    • design the granularity of each data component, whereby their granularity is at a level where each instance of a component can be uniquely identified and retrieved.
    • absence of instance aliasing. i.e., no means exist whereby an identification produces more than one instance of a component.
  2. Absence of instance crosstalk. There does not exist the necessity to use one or more other instances of a component to contribute to identifying an instance of a component.
  3. The unity and identity of data components/dimensions.
    • Presence of component de-aliasing. There must exist one definition whereby a component/dimension can be uniquely identified. Which is the primary definition of a component;
    • where the primary definition will not result in exposing sub-dimensions or member-components that are not part of an intended component;
  4. Unique means of component dealiasing. There must exist one, and only one, such component de-aliasing definition for a component.
  5. There exists one, and only one, definition interface or contract to identify a parent component in a hierarchical relationship of components.
  6. Absence of component crosstalk. There does not exist the necessity to use a member of another component to contribute to the definitive identification of a component.
    • In such a parent-child relationship, the identifying definition of a parent must not depend on part of the set of member components of a child. A member component of a parent's identity must be the complete child identity without resorting to referencing any or all of the children of a child.
  7. Preempt bi-modal or multi-modal appearances of a data-model.
    • When there exists two candidate definitions of a component, it is an obvious sign that there exists two different data-models being mixed up as one. That means there is incoherence at the data-model level, or the field level.
    • A field of applications must use one and only one data-model, coherently.
  8. Detect and identify component mutation. Unless you have performed statistical component analysis of huge data, you probably do not see, or see the need to treat, component mutation.
    • A data-model may have its some of its components mutate cyclically or gradually.
    • The mode may be member-rotation or transposition-rotation.
    • Member-rotation mutation could be distinct swapping of child components between components. Or where completely new components would have to be defined.
    • Transpositional mutation would manifest as a dimensional-member mutating into an attribute, vice versa.
    • Each mutation cycle must be identified as a distinct data-modal.
  9. Versionize each mutation. Such that you can pull out a previous version of the data model, when perhaps the need arise to treat an 8 year old mutation of the data model.

In a field or grid of inter-servicing component-applications, there must be one and only one coherent data-model or exists a means for a data-model/version to identify itself.

Are we still asking if we could use Interface Constants? Really ?

There are data-normalization issues at stake more consequential than this mundane question. IF you don't solve those issues, the confusion that you think interface constants cause is comparatively nothing. Zilch.

From the data-model normalization then you determine the components as variables, as properties, as contract interface constants.

Then you determine which goes into value injection, property configuration placeholding, interfaces, final strings, etc.

If you have to use the excuse of needing to locate a component easier to dictate against interface constants, it means you are in the bad habit of not practicing data-model normalization.

Perhaps you wish to compile the data-model into a vcs release. That you can pull out a distinctly identifiable version of a data-model.

Values defined in interfaces are completely assured to be non-mutable. And shareable. Why load a set of final strings into your class from another class when all you need is that set of constants ??

So why not this to publish a data-model contract? I mean if you can manage and normalize it coherently, why not? ...

public interface CustomerService {
  public interface Label{
    char AssignmentCharacter = ':';
    public interface Address{
      String Street = "Street";
      String Unit= "Unit/Suite";
      String Municipal = "City";
      String County = "County";
      String Provincial = "State";
      String PostalCode = "Zip"
    }

    public interface Person {
      public interface NameParts{
        String Given = "First/Given name"
        String Auxiliary = "Middle initial"
        String Family = "Last name"
      }
    }
  }
}

Now I can reference my apps' contracted labels in a way such as

CustomerService.Label.Address.Street
CustomerService.Label.Person.NameParts.Family

This confuses the contents of the jar file? As a Java programmer I don't care about the structure of the jar.

This presents complexity to osgi-motivated runtime swapping ? Osgi is an extremely efficient means to allow programmers to continue in their bad habits. There are better alternatives than osgi.

Or why not this? There is no leakage of of the private Constants into published contract. All private constants should be grouped into a private interface named "Constants", because I don't want to have to search for constants and I am too lazy to repeatedly type "private final String".

public class PurchaseRequest {
  private interface Constants{
    String INTERESTINGName = "Interesting Name";
    String OFFICIALLanguage = "Official Language"
    int MAXNames = 9;
  }
}

Perhaps even this:

public interface PurchaseOrderConstants {
  public interface Properties{
    default String InterestingName(){
       return something();
    }
    String OFFICIALLanguage = "Official Language"
    int MAXNames = 9;
  }
}

The only issue with interface constants worth considering is when the interface is implemented.

This is not the "original intention" of interfaces? Like I would care about the "original intention" of the founding fathers in crafting the US Constitution, rather than how the Supreme Court would interpret the written letters of the US Constitution ???

After all, I live in the land of the free, the wild and home of the brave. Be brave, be free, be wild - use the interface. If my fellow-programmers refuse to use efficient and lazy means of programming, am I obliged by the golden rule to lessen my programming efficiency to align with theirs? Perhaps I should, but that is not an ideal situation.

Related