Is the any difference in performance and/or any other benefits we can get when using final keyword with constant utility class. [ This class contains only static final fields and private constructor to avoid object creation]
public class ActionConstants {
private ActionConstants() // Prevents instantiation
{ }
public static final String VALIDFIRSTLASTNAME = "[A-Za-z0-9.\\s]+";
public static final String VALIDPHONENUMBER = "\\d{10}";
...
...
}
Only diffrence is class is made final
public final class ActionConstants {
private ActionConstants() // Prevents instantiation
{ }
public static final String VALIDFIRSTLASTNAME = "[A-Za-z0-9.\\s]+";
public static final String VALIDPHONENUMBER = "\\d{10}";
...
...
}
I like to know, is there any benefits there in using final and what is the correct way to define class for constants.
If you are looking for improved performance you are better off pre-compiling your patterns like
Using a final or not is, very small compared to the cost of using a regular expression.
You should avoid using "classes for constants". It means a bad ddesign. Place constants in classes that operate with them. Avoid using public constants as well. It should be exception, not a normal practice.
To use a class for constants is uncommon. In most cases an interface is used. This would be accessible by
ActionConstants.VALIDFIRSTLASTNAME
:Since Java 5 you can also use an enum. An enum can have members or extended functionality.
The second example uses a simple member (here with a generic approach if you have different constant types, else you can also use a
String
member):The last example uses extended functionality when all constants are of the same type. You can use it like
ActionConstants.PHONENUMBER.isValid("0800123456")
:Both versions allow the use of static imports.
There is no benefit. It does not change anything regarding your
static final
attributes.When a class is made final, the compiler can take advantage of this for overridable methods (static methods cannot be overriden, at best, they hide those one in inherited classes).
Since the class is final, the compiler knows none of its method can be overriden. So, it can compute cases where polymorphism code does not need to be generated (i.e., the code finding the right 'version' of the overriding method according to the object instance at runtime). Hence, an optimization is possible.
If you want to make a class truly unique, you can use something like this:
And if you are not interested in a class instance at all, just put all your constants in an interface.
There is no real benefit, but it does enforce your expectation that nothing extends your class. That might make it easier in the long term to, for example, search your code for all uses of the constants since they will be guaranteed to be XXX.abc and not YYY.abc where YYY extends XXX.