I have no doubt that you are using the "Constant Interface Antipattern"
In any case, if you define "static final int MAX = 10", the compiler is likely to fold that 10 into code. Try the following: compile and run this code. Change the value of MAX and compile only I, then run again.
As far as worrying about separate copyies of constants, why worry? I doubt if that could be a space issue.
There is no emoticon for what I am feeling!
Joined: Dec 16, 2003
hi thank you,
my consern with the space is my interface consists more than 100 variable and my most of the application classes implements this interface, so i think it as a poor design instead of that access directly Appinterface.var where ever it is required
Joined: Sep 16, 2005
I think the results of inheriting the anti-pattern constants interfaces versus using the interface directly will be the same. Inheriting itself doesn't imply copying. I think what whereever you *use* a constant, there may be constant folding, but that doesn't take up space and in fact may save in both space and time as it facilittates further optimization.
On the other hand, good OOD would suggest that if these constants are global and not associated with any one class you should define them in a class:
If you don't like writing AppConstants.MAX elsewhere, you can use static imports.
Client code still will probably fold in constants at compile time. You can test that with the following program: run C, edit and compile only AppConstants and run C again.
To avoid this behavior (to make it easier to recompile and run, versus any worries of runtime size), you can write the constant class as follows.
If your class implements the constants interface, it becomes part of your concrete class's public API, which is not a good practice. Implementation details, such as using the static members of another class, should not leak into public APIs. As someone mentioned, if you are on 5.0, you can use static imports.
Originally posted by thomas davis: String is immutable,then why do we need to make it a public static final?
The "final" modifier applied to a variable means the value of the variable can't be changed. This has nothing to do with whether the variable contains a reference to a mutable or immutable object. Example:is legal because name isn't final. No string objects are changed, they are immutable anyway. Butis not legal because name is final.