java - Constant Interface Anti-Pattern Clarification -


i read somewhere having interface common project constants bad practise , known constant interface anti-pattern. if understood correctly, reason provided once implemented, class expose these constants public.

well, don't understand need 'implementing' in first place. isn't possible use these static constants directly? why should have go through trouble of import static when can like:

interface constants {     public static final int foo_1 = 1;     public static final int foo_2 = 2; }  public class test {     public static void main(string[] args) {         system.out.println(constants.foo_2);     } } 

i appreciate guidance me understand bit more.

the arguments against "constant interface pattern" stylistic. can use constant interface in java if suits need , in fact java libraries include few of these (though considered poor examples shouldn't repeated).

the reasons why constant interface considered many "anti-pattern" enumerated in effective java, 2nd ed. briefly, of reasons use of interfaces discouraged include:

  • namespace pollution. named constants appear in namespace of implementing classes subclasses.

  • interfaces should define types. in java, of major types in project should represented interfaces. constant interface nature not define type.

  • noninstantiable classes static import. declaring constants static final fields in class (rather interface) achieves same objectives declaring them in interface. doing not create namespace pollution class. if desired, these constants can used without qualifying class name using static import declaration.

  • interfaces should specify behavior. interface supposed define contract between interface , implementing classes. implementing interface supposed class can do. constant interfaces not follow pattern.


Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -