日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Item 13 Minimize the accessibility of classes and members

發布時間:2025/3/8 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。