Item 13 Minimize the accessibility of classes and members
區分好的模塊和不好的模塊最重要的因素是看這個模塊對于其他模塊而言是否隱藏內部數據和其他細節。好的模塊會把所有細節隱藏起來,把API和實現隔離開來,模塊之間用API通信。這就是information hiding或者封裝(encapsulation)。是軟件設計基本原則之一。
information hiding最大的意義在于it decouples(解耦) the modules that comprise a system. 這樣模塊就能獨立開發、測試。提高了可重用性。
Java中很多facility協助了信息隱藏,比如訪問控制access control,決定了類,接口,成員的accessibility。
The rule of thumb: **盡可能使每個類或者成員不被外界訪問。**也就是給最小的訪問級別。
頂層類和接口
Top level(non-nested)的classes and interfaces,只有兩種可能的訪問級別:
- package-priavte(筆者注:也就是default) The member is accessible from any class in the package where it is declared
- public
成員(fields, methods, nested classes, and nested interfaces)
- private—The member is accessible only from the top-level class where it is declared.
- package-private—The member is accessible from any class in the package where it is declared. Technically known as default access, this is the access level you get if no access modifier is specified.
- protected—The member is accessible from subclasses of the class where it is declared (subject to a few restrictions [JLS, 6.6.2]) and from any class in the package where it is declared.
- public—The member is accessible from anywhere.
-
從package-private變成protected時,accessibility會大大增強。protected members應該盡量少用。
-
子類中覆蓋的方法的訪問級別不能低于父類的那個。特別的,對于接口來說,接口中所有的方法都隱含著公有訪問級別;所以如果一個類實現了接口,接口中所有方法在這個類中也必須被聲明為公有的。
-
instance field永遠不能是public的。 Classes with public mutable fields are not thread-safe. 這一點也就解釋了之前我討論的為什么android中的context不能寫成 public static Context context;(當然對于android來說,private也不行,因為context不能是static)。這一點我還是不太明白,主要不明白instance field是啥,與之對應的static field是啥。
-
同樣的建議適用于靜態域。
總之,防止任何散亂的類、接口、成員變成API的一部分。除了Public static final的特殊情形,public class都不應該含有public fields. 還要確保public static final域的對象都是不可變的,比如,不能定義一個public static final Things[] VALUES = {...};因為非0數組是可變的。
轉載于:https://juejin.im/post/5a31341851882535cd4ad56a
總結
以上是生活随笔為你收集整理的Item 13 Minimize the accessibility of classes and members的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 为何有些程序员总是想要“干掉”产品经理?
- 下一篇: 二.编写第一个c#程序(注释,命名空间,