java constants

Wed, Mar 2, 2005

One of the pig awful things about Java, apart from it’s lack of a preprocessor, is it’s complete lack of includes. I can sort of understand the lack of a preprocessor as the one for C/C++ is mainly used for platform specific builds, which Java is supposedly immune to. However, the lack of #include is a real pain, mainly for people coming from a C/C++ background and who are used to defining application-wide constants. So, how do you do it in Java?

The most popular approach is to define all your constants in an interface: public interface Constants {   public static final String HELLO_WORLD = “Hello World!"; } and then use that interface in your classes: public class UserOfConstants implements Constants {   public static void main(String[] args) {     System.out.println(HELLO_WORLD);   } }

but this is known as an “anti pattern” and purists will jump up and down about it. One criticism is “interfaces provide services that consumers may wish to use”, i.e. they define functionality. It’s a semantic thing. UserOfConstants doesn’t “implement” anything, it just “includes” the stuff in Constants. Of course, Java doesn’t have the concept of includes so you’re stuck.

The purists will then calm down and tell you to use a class to define your constants: public class Constants {   public static final String HELLO_WORLD = “Hello World!"; }

but as you can see it’s identical to the interface, with one exception - “interface” has become “class” and the class loader will then load that class’s hierarchy, all the way down to Object, just so you can use a constant. A waste? I’ll leave that up to the reader to decide.

Now, however, “Tiger” (Java 1.5) moves one step along the road to includes, with static imports: public interface Constants {   public static final String HELLO_WORLD = “Hello World!"; } Notice we’ve binned the class and gone back to the interface, so it wasn’t that bad an idea in the first place but instead of “implementing” the interface, which, according to the purists is a demonic use of the language, we “import” it: import static Constants.*;

public class UserOfConstants {   public static void main(String[] args) {     System.out.println(HELLO_WORLD);   } } At last! Java has #include! I’ve got my C++ life back and the purists are happy :)

We can take it a stage further and go one better than #include though. The code above is nice and it works but it’s not that clear where HELLO_WORLD is coming from if we have more than one import static. We can make the code more maintainable by just importing the constants we’ll need: import static Constants.HELLO_WORLD; So, when Java 1.5 arrives for the Mac, I’ll be able to use #include and even make my code that wee bit more readable. Now, when the Mac gets 1.5 is anyone’s guess.

#include <osx_jdk15 .h>

comments powered by Disqus