Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Regarding constant interface pattern and enum  RSS feed

 
surya.raaj prakash
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Friends,
what is difference between constant interface pattern and enum type? and which is better solution for declaring constants?
 
Ulrika Tingle
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 449
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Joshua Bloch's "Effective Java" contains one detail topic against Constant Interface pattern.
 
Rob Spoor
Sheriff
Posts: 21095
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!