Thursday, November 3, 2011

Encapsulate Your Constants

Does your application have a "Constants" file? It's a class with a list of constants used across the application? It's a large file with a list of Strings that don't have any relationship to one another and has a bunch of comments and carriage returns to "organize" the file.Move them.

Exposing a public constant allows developers to access state from all areas of the application. => Limit global variables and global constants. Move them into the class that is responsible for using the constant.

Constant files grow over time => Don't introduce the constants file pattern. Your constants are related to some domain concept. Are they Roles? Are they keys for a cache or session storage? Move them to the correct class and make them private.

Constants are an implementation detail => Don't force you teammates to find the correct key name to access some session variable. Create a method to get and set the value. The storage provider and index is an implementation detail and should be wrapped in a method that knows the storage key and provides appropriate casting.

Do yourself and your team a favor and move the constants into the classes that need them.