可以參考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常用的情境:
- Internal Invariants
- Control-Flow Invariants
- Preconditions, Postconditions, and Class Invariants
同樣的情況,封裝(encapsulation)也是在確保 invariant的合理性。因此有一個考題討論封裝(encapsulation)的目的,敘述「encapsulation enables class implementation to protect its invariant」應該是正確的。
沒有留言:
張貼留言