This week's book giveaway is in the General Computing forum.
We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Regarding constant interface pattern and enum Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Regarding constant interface pattern and enum " Watch "Regarding constant interface pattern and enum " New topic
Author

Regarding constant interface pattern and enum

surya.raaj prakash
Ranch Hand

Joined: Oct 30, 2009
Posts: 76
Hi Friends,
what is difference between constant interface pattern and enum type? and which is better solution for declaring constants?
Ulrika Tingle
Ranch Hand

Joined: Nov 24, 2009
Posts: 92
surya.raaj prakash wrote:Hi Friends,
what is difference between constant interface pattern and enum type? and which is better solution for declaring constants?


One reason enum was introduced in Java in the first place was to avoid the Constant Interface pattern. One could say that the "prefer composition over inheritance" principle was followed. The Constant Interface pattern is based on that you inherit a bunch of constants. That's not how enums are used. They cannot even be inherited.
Muhammad Khojaye
Ranch Hand

Joined: Apr 12, 2009
Posts: 341
Joshua Bloch's "Effective Java" contains one detail topic against Constant Interface pattern.


http://muhammadkhojaye.blogspot.com/
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19232

The constant interface pattern is in fact an anti-pattern that should not be used. A final class with a private constructor is much better; java.sql.Types is an example.

An enum should be preferred because it also limits the number of values; using constants ints or Strings allows you to pass any int / String and you need to validate any arguments. Using an enum the only invalid value could be null. Only if you need to store constants of different types or do not care about invalid values should you consider using the constant class pattern these days.


SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Regarding constant interface pattern and enum
 
Similar Threads
what results byte code in java
Best practice: static import
Confusion about class members
Effective Java: Typesafe enum pattern
enum