Static final “constant” variables should be in upper case, with the words separated by an underscore.

eg.

public static final String ATTRIBUTE_PUBLISH_DATE = “publishDate”;

A constant is just a variable that never changes, so the usual naming conventions apply to identify the concept of what the variable represents.

public static final int TWO_THOUSAND_AND_FORTY_EIGHT = 2048;
public static final int TWENTY_FIVE = 25;
public static final String SURNAME = “surname”;
public static final String SEARCH = “search”;

The above variables had no aparrent purpose until an investigation showed where they were used in the code.  Developers rarely have time for detective work.  A quick refactor made the usage clearer:

// public, implies external use
public static final int MAX_HTML_SIZE = 2048;
public static final int ITEMS_PER_PAGE = 25;
public static final String ATTRIBUTE_SURNAME = “surname”;

// private, implies internal use only
private static final String INITIAL_SEARCH_TEXT = “search”;   

Tip: for static final constants, the public and private modifiers are used to tell other developers where the definition is intended to be used:

  • public definitions are referenced from outside the class, defined to illustrate a dependency between two otherwise independent classes.

  • private definitions are internal to the class only, defined to make the class file easier to maintain, and perhaps to illustrate a dependency between two otherwise independent methods within the same class.

blog comments powered by Disqus