1. Minimize the accessibility of classes and members
- 可以宣告為越私有就越私有
- 只屬於某個class會用到的class就用inner class
- member 盡量為private
- subclass不可以比superclass更private
- interface一定是public
- instance fields 一定不可以是 public
- static final fields也不可以是public, 因為object refer到的object會被改到
2. In public classes, use accessor methods, not public fields
3. Minimize mutability
- 使一個class immutable
no modify method, can't be extended, all fields final, instance fields是object reference 要小心指到的物件不會被改
- 沒有thread, synchronization的問題, 可以被share
- 可以拿來被當做常數使用
- 在static factory可以cache, 因為同一個value的物件一定是唯一的
- 會有performance的問題
- mutable companion class, 就像String and StringBuilder
- 用 private constructor 而不要用final
- Serializable要注意 readObject / readResolve
- 如果不能完全做到immutable, 也要盡量減少可以被修改的fields
4. Favor composition over inheritance
- 只有在同一個package or 有特別說明使用來被繼承的class, 才去繼承
- 缺點
1. 違反 encapsulation, 因為要說清楚人家才好繼承
2. 容易因為superclass修改就傷害了繼承的class, 甚至可能不能compile
- 只有確定是 is-a 關西, 才考慮用繼承
5. design and document for inheritance or else prohibit it
- 必須說明有哪幾個methods有用到overridable methods
- 說明這個method應該如何被override的說明
- 自己寫個subclass測試看看
- Constructor不可以使用overridable method
- Cloneable & Serializable 不繼承
6. Prefer interfaces to abstract classes
- 現有的class較容易改寫成某個interface
- interface可以多個
- 最好是 interface + abstract class => skeletal implementation
7. Use interfaces only to define types
- 不要用來定義 Constants
8. Prefer class hierarchies to tagged classes
- 同一個class不要同時可以變成兩種物件
9. Use function objects to represent strategies
10. Favor static member classes over nonstatic
- static member class
- non-static member class
- anonymous inner class => 一定要繼承或是implement某個interface
- local classes
About Me
星期一, 6月 30, 2008
Effective Java - Chapter 4 Classes and Interfaces
訂閱:
張貼留言 (Atom)


0 意見:
張貼留言