Java 8: When the use of Interface static methods becomes a bad practice? -


from java 8, can have default methods , static methods in interfaces.

the constant interface pattern poor use of interfaces known constant interface antipattern.

>effective java, item 17 :

the constant interface pattern poor use of interfaces. class uses constants internally implementation detail. implementing constant interface causes implementation detail leak class's exported api. of no consequence users of class class implements constant interface. in fact, may confuse them. worse, represents commitment: if in future release class modified no longer needs use constants, still must implement interface ensure binary compatibility. if nonfinal class implements constant interface, of subclasses have namespaces polluted constants in interface.

there several constant interfaces in java platform libraries, such java.io.objectstreamconstants. these interfaces should regarded anomalies , should not emulated.

if use of constant interfaces bad practice, when use of interface static methods becomes bad practice ?

the main problem constant interfaces isn't interface contains lot of constants.

it's when classes implement interface can access constants easier:

public interface foo {     public static final int constant = 1; }  public class notokay implements foo {     private int value = constant; }  public class okay {     private int value = foo.constant; } 

class notokay not creates fake relationship between interface foo , (there nothing implement there), constant values become part of public api.

(this practice lot more common before static imports introduced in java 5.)

with static interface methods there no point implementing interface because can't access them in same manner: static interface methods not inherited.


Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -