Abstract Data Type -ADT- and ObjectOriented Programming -OOP-
Designing Specification
一個完整的方法包括兩個方面
- 方法的規約spec
- 方法的實現體implementation
- 代碼本身就蘊含着你的設計決策,但是遠遠不夠
- 代碼中蘊含的“設計決策”:給編譯器讀
Specification
內容
What the method does, not how it does it
Interface (API), not implementation
- 前置條件:對客戶端的約束,在使用方法時必須滿足的條件
- 後置條件:對開發者的約束,方法結束時必須滿足的條件
- 契約
- 如果前置條件滿足了,後置條件必須滿足
- 前置條件不滿足,則方法可做任何事情
clauses | keyword |
---|---|
precondition | requires |
postcondition | effects |
parameter | @param |
results | @return @throws |
mutating methods 的 spec
在後置條件中聲明所做的修改
除非在後置條件裏聲明過,否則方法內部不應該改變輸入參數
程序員之間應達成的默契:除非spec必須如此,否則不應修改輸入參數
spec中不應出現什麼
A specification of a method can talk about the parameters and return value of the method, but it should never talk about local variables of the method or private fields of the method’s class.
Failing fast
When our precondition is violated, the client has a bug.
We can make that bug easier to find and fix by failing fast, even though
we are not obligated to do so.
using assert to fail fast
寫出規約的原因
第一:自己記不住
第二:別人不懂
行爲等價性
The notion of equivalence is in the eye of the client (站在客戶端視角看行爲等價性). 行爲不同, 但對用戶來說“是否等價”?
根據規約判斷是否行爲等價
若兩個函數符合同一個規約,則它們等價。
優點
- 註釋形式的“設計決策”:給自己和別人讀
- 程序與客戶端之間達成的一致,the implementer is responsible for meeting the contract, and a client that uses the method can rely on the contract
優點 - 精確的規約,有助於區分責任
- 客戶端無需閱讀調用函數的代碼,只需理解spec即可
- 規約可以隔離“變化”,無需通知客戶端
- 規約:扮演“防火牆”角色