Re: Making String variable and value available for all Classes
Lew wrote:
Qu0ll wrote:
A better alternative is to use an interface if the user name is
constant like:
public interface UserConstants {
public static final String USER_NAME = "sahm";
}
This terrible idea is known in the industry as the Constant Interface
Antipattern.
That anti-pattern also uses inheritance to access the constants, and
that use of inheritance is the biggest no-no in the anti-pattern, afaik.
class MyStuff implements UserConstants // evil!
{
public String getUserName() {
return USER_NAME; // evil!
}
}
<http://en.wikipedia.org/wiki/Constant_interface>
Interfaces should be used to define types, not to hold constants. Use
classes to hold constants.
The only difference that I can see between classes and
interfaces is you can't make the latter final, which is really the
point, I think. So if you're going to say "uses classes," then you
really ought to say "use final classes" to give Qu0ll the whole picture.
A private constructor is the best way of doing this because it also
prevent instantiation, which can also be an anti-pattern for classes
with only static members.
public class UserConstants {
private UserConstants() {} // make class final and non-instantiable
public static final String USER_NAME = "sahm";
}