The last couple of days I’ve been involved in what I would essentially term a code review of some things our off shore team recently completed. To say there were some issues would be a bit of an understatement and it has certainly helped cement the need for continuous integration, frequent review, and a strong test suite. While I expected some odd use of inheritance, the empty interfaces caught my eye and I spent longer than I like explaining why YAGNI would be the team’s default position on pretty much anything. But none of that is really worthy of a blog post - that’s just run of the mill coding stuff. No, the real inspiration was this little gem:
public class Constants {
public interface UIConstants {
public static final String foo = "foo";
public static final String bar = "bar";
}
}
Now, I know some people think that interfaces are the cat’s meow for storing constants, heck, I even did it once in a past life (I was young, I needed the money) but I’ve vowed never to follow that antipattern again. Don’t just take my word for it - Joshua Bloch calls it out in his must read Effective Java (I for one can’t wait for the updated version). I’ve done my part to eradicate this erroneous use of interfaces but when I saw the code above I was floored.
Frankly, I’m a little surprised it compiles but unfortunately it does. Of course I found myself asking *why* anyone would even think to use this approach. Wait, I can hear it know “we only have one place to go to look for constants and we have namespaces too.” Um, OK, then please explain why there were a couple of other interfaces that were also called Constants and did you catch the whole antipattern comment? Furthermore, explain why you think it makes any sense at all to have an interface as a member of a class. Talk about abusing the constructs of Java.
Needless to say, we extracted those so called interfaces into real honest to goodness classes that couldn’t be instantiated. And for those of you that will complain about how painful it is to write UIConstants.foo
in your code, have you heard about static imports yet? Should you go down this road though *please* don’t go overboard; as the Sun guide says:
If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the static members you import. Readers of your code (including you, a few months after you wrote it) will not know which class a static member comes from.
Needless to say, it’s been an interesting few days reviewing this code - I wait with bated breath to see what next week brings.