Java Constants – Not In The Interface
I was working on some code refactoring on a massive codebase when I was faced with the issue of where to put constants for the default values of business rules. This issue has been a constant subject of design discussion in java since I can remember, and definitely over a decade for myself. Doing “object” code, you try your hardest to avoid big “global” files. But sometimes you have to have a central, global location to put constants. In my case, refactoring the same rule spread out over several classes each containing:
public static final boolean DEFAULT_VALUE = false;
So you can see the problem here — if this definition sits in several classes there’s a chance any change will be missed and you’ll have breakage. There should be one definition to rule them all.
Now one place you *might* be tempted to drop your constants in is an interface. I’ve seen this before, but is decidely in my opinion a bad pattern since interfaces are generally used to define relationships to other components and this could be construed the same thing as defining a complete method in an interface. It was unfortunate, imo, that this had already been done in the code and it’s a good policy to match the patterns — even bad ones — until you can get around to refactoring them out. I decided to refactor. And the discussion of where to put Java application constants has been going on fever — for instance in this older venerable C2 site article – interfaces for defining constance – c2.com.
Some other solutions in the recent codebases I’ve worked on:
- property files
- enumerations
- abstract classes
- static classes
- depending on the scope – class level
And that is the key — “what is the scope?” Global/application/multi-context scope becomes more challenging in design.
In many of the web applications I’ve worked on if we’ve used the constants on the backend, we’d make enumerations or a static class with the constants. Then if you need to expose them, say to tag libraries or the front end, you can import them or make a service to expose them. Enumerations lend themselves to this quite well.
The important thing is to get that default centralized if it is a business rule. Multiple definitions of a default value, or any value, become problematic. I’ve seen implementations of lists of statuses kept in string constants, enumerations, and a database lookup table all in the same application.
The company paid a lot of money to fix that.