2019年4月5日 星期五

variant 與 invariant

variant 與 invariant兩個單字,如果直接查字典,會得到「variant(變量) 」與「invariant (不變量)」的解釋。但「invariant (不變量)」並非指不會改變,而是指改變的結果是符合程式設計的假設與前提。否則就是常數了。
可以參考https://coderanch.com/t/699207/java/Relationship-class-invariants-encapsulation的見解:

What do you think invariants means? It doesn't mean that fields don't vary. It means features which remains true at all times. For example, one of the invariants of a kettle is that its water content is never negative, so at all times content ≥ 0. You can only maintain that invariant if the content field is inaccessible to outside code, and all methods modifying it maintain that invariant. So, both concepts are separate, but encapsulation is necessary to preserve the invariants.

原廠教材在講授Assert
https://docs.oracle.com/javase/7/docs/technotes/guides/language/assert.html (斷言)時,就舉出3個Assert常用的情境:
  1. Internal Invariants
  2. Control-Flow Invariants
  3. Preconditions, Postconditions, and Class Invariants
需要斷言的是變數值的改變在設計的合理範圍內,若是「常數」何須斷言?

同樣的情況,封裝(encapsulation)也是在確保 invariant的合理性。因此有一個考題討論封裝(encapsulation)的目的,敘述「encapsulation enables class implementation to protect its invariant」應該是正確的。







沒有留言:

張貼留言