2017年11月3日 星期五

Day2-1 - Encapsulation 封裝

5.1 Develop code that implements tight encapsulation, loose coupling, and high cohesion in classes, and describe the benefits.

OO的好處是,可以改變程式碼的implementation,但又不會破壞已經使用到此程式的程式碼。
藉由隱藏實作method的細節,可以重新develop程式碼,且不須要強迫別人修改已經寫好的code。
以下三種方法可以讓程式碼擁有maintainability, scalability, extensibility
  1. 保護instance variable (private)
  2. 建立setter methods(mutators) and getter methods(accessor)操作變數,強迫使用這些methods對variable進行存取
  3. 對於methods使用JavaBeans的命名原則(set property , get property)
- 就算目前實作隊setter method和getter method沒有做任何判斷,只是回傳值或設定private instance variable,但OO的好處就是可以改變想法,之後可以再新增判斷在methods內而不會破壞API。一個好的OO設計就是要求為未來做準備。永遠都要確保caller (other developers)使用method存取instance variable。

沒有留言:

張貼留言