Effective Java Item 19 note

Use interfaces only to define types

Arwii
mycodingjourney
3 min readJun 15, 2018

--

interface在使用上應該將其視為一個type,只要有class去implement它,我們就可以依照這個type裡面的規定去使用它們的method。interface應該就只可以有這個功用。也就是說不要在interface裡面用

在java.io.ObjectStreamConstants中,把interface當成了constant interface,這個interface就只有constants。

public interface ObjectStreamConstants {
final static short STREAM_MAGIC = (short)0xaced;
final static short STREAM_VERSION = 5;
final static byte TC_BASE = 0x70;
...
}

一則讓使用者會困惑到底要不要implement它,如果不小心implement了,那麼萬一裡面的constants搬走了,還是要繼續implement該interface只為了binary compatibility。( 這個字眼一開始看到有點黑人問號,在Android上面開發久了對於update jar都是透過直接update apk,比較少遇到換jar的情況,不過如果用線上patch release的jar角度來看的話,就會遇到這個問題沒錯。

P.S java 8開始在interface裡面support default關鍵字,就是用來解決這個相容性問題。但default method不能使用field成員,因為interface本來就不能定義field了。)

二則是name space也會被這些constants給污染,不過這點應該還好,除非你的命名太簡單。

那麼有兩種方式可以把constants從interface中拿走。

  1. 把constants放到相關緊密的class中,然後有必要的話用enum去包住這些constants
    public class test{
    enum cons{
    a,b,c
    }
    }
  2. 把constants放到不可被實例化的utility class中
    a. constructor是private
    b. 變數都大寫,且都是public static final
    c. 如果這些constants數量很多,可以用static import去省掉一些class name的程式碼
public class Utils {
private Utils()
public static final int A = 1;
...
}

--

--

Arwii
mycodingjourney

Try not to become a man of success, but rather try to become a man of value — A. Einstein