Few days ago I was thinking about optimizing the use of constants (usually of String type) inside projects to avoid proliferation of public static final String declarations on various classes (with a limited control over duplicates) but giving at the same time developers a way to increase readability of constants in their code.
The reason for this post is that I want to know your opinion on this strategy, that on my eyes appear elegant and clear but may bring some drawbacks.
public class Constants{
private static ObjectName_Constants objectNameConstants;
public static ObjectName_Constants ObjectName{
get {
if(objectNameConstants == null){
objectNameConstants = new ObjectName_Constants();
}
return objectNameConstants;
}
}
public class ObjectName_Constants{
public String CustomField_AValue { get { return 'aValue'; } }
public String RecordType_ADevName { get { return 'aDevName'; } }
}
}
The class is basically shaped as follows:
This brings to a cool looking:
String myDevName = Constants.ObjectName.RecordType_ADevName;
This way we have the following pros:
- Clear hirearchy for constants
- More readable constants names (they are all getters but are used as constants, so no need for upper case)
- Heap space is allocated on constants only if they are actually used
- Centralized place for common constants
And these are the cons:
- More quantity of Apex used to write a constants
I’m curious to get some feedbacks.
Leave a Reply