grokking hard

code smarter, not harder

Homeless Constants

Posted at — 2013-Jan-12

Today, one of my colleague came to me and asked: “Hey, do we have a place to put a general constant?”. “What?” - I said. “A class, you know, to put all constants that do not particularly belong to anywhere, something general” - He replied. Then I looked at him and said: “Dude, we got nothing such as general constants”.

The sad truth is, in our current project, we got a class named GeneralConstants just for putting all those constants in it. It got constants for entity String property lengths (seriously!!), panels’ names, bunch of constants that are irrelevant and only used exclusively with some specific modules. Even worse…

public final static String CLICKED = "CLICKED";
public final static String REMOVED = "REMOVED";

..and why stop if you can have constant for one single character.

public final static String BLANK = " ";
public final static String COLON = ";";

It really got ridiculous to see:

String myName = firstName + GeneralConstants.BLANK + GeneralConstants.COLON + GeneralConstants.BLANK + lastName;

In my opinion, when you got a constant and wonder where you should put it for others to use, I got just a right place for it: inside the module using that constants and keep it private.

Not all constants are reusable and not all constants should be public. The first time you create a constant, keep it private inside your module and try real hard to encapsulate the use of it. If it really needs to be public, then it deserves its own place.

It should be EntityStringLengths.

It should be InvokablePanels.

It should be AllowedDialogActions.

In case of BLANK and COLON, just use the freaking literal Strings. Making them constants is overkill. They make verbose & hard-to-read code. Moreover, doing this does not have any benefits in terms of performance. Please don’t do this.

Next time when you got a constant. Ask yourself: