Android, Best way to provide app specific constants in a library project?

后端 未结 3 1796
走了就别回头了
走了就别回头了 2021-02-13 12:26

I am creating a library project for a number of android apps. The apps all have some common functionality that I wish to include in the library project but the library project f

3条回答
  •  有刺的猬
    2021-02-13 12:48

    define them as enum's in your library project, like

    public enum Planet { MERCURY, VENUS, MARS }
    

    android proper takes another approach, the dreaded constant interface, like,

    interface Planets {
      static final int MERCURY = 1;
      static final int VENUS = 2;
      ...
    }
    

    however, this is a well-known java anti-pattern (constant interface, and is covered in detail in Effective Java, i quote,

    The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class’s exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface.

    if you need the constants to have int values for some reason, and calling toString() on the enum isn't sufficient, you can give the enum's a extra information like,

    public enum ZipCode {
      LYNNWOOD(98036), SAN_JOSE(95112), ...;
    
      private int zipCode;
    
      private ZipCode(int zipCode) { this.zipCode = zipCode; }
    
      public int getZipCode() { return zipCode; }
    }
    

    Note that enum's are slightly less performing than integer constants, but from a code organization and clarity perspective they are far superior.

提交回复
热议问题