work

Homeless Constants

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”. 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

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 fucking literal String. It is not making them reusable. It is overkill, too much fine-grained. They produces verbose & hard-to-read code. Moreover, doing this does not benefit you any performance. Please don’t do this.

Next time when you got a constant. Ask yourself:

  • Am I really going to use this constants somewhere else?
  • Could I encapsulate the use of this constants via methods?
  • What should I name the class containing the constant to make everybody know what it is?