About Me

我的相片
Mr. Pigg
Taipei, Taiwan
檢視我的完整簡介

星期二, 7月 29, 2008

Effective Java - Chapter 7 Method

1. Check parameters for validity
- For exported API: check parameters first
- IllegalArgumentException, IndexOutOfBoundsException, NullPointerException
- For unexported API: Assertion
- 小心不要讓check parameters影響performance
- Document it

2. Make defensive copies when needed
- 確保物件不會被傳進來的人改掉
- 不是Final class不要用clone
- return 物件最好也用defensive copy
- 最好是immutable

3. Design method signatures carefully
- Class不要有太多method
- Method不要有太長的parameters < 4
- 方法: break it, Helper, Builder
- 參數favor interfaces over classes

4. Use overloading judiciously
- 使用哪一個overload method是在compile時決定的
- Overriden method則是在run-time決定的
- 盡量不要使用參數數量相同的overload method
- 或是兩個決定不相容的參數也可
- 小心autoboxing/autounboxing
- 常因為class evolusion導致產生兩個互通參數的overload method, 只要的做的事相同即可

5. Use varargs judiciously
- 用 (int first, int ... remain)可以省去檢查參數的麻煩
- 不要把原本用array傳參數的改成 varargs,會出錯
- performance issue

6. Return empty arrays or collections, not nulls
- client可以不用檢查null, 避免錯誤

7. Document for all exposed API elements
- summary description
- precondition, postcondition
- @param, @return @throws
- Thread safety
- Serialization
- Class for inheritance
- @code, @literal
- Generic ,Annotation, enum

0 意見: