What is a class invariant in Java?

后端 未结 3 903
刺人心
刺人心 2020-12-22 17:16

I googled the topic, but besides Wikipedia I didn\'t find any further useful documentation or articles.

Can anybody explain to me in simple words what it means or r

3条回答
  •  醉话见心
    2020-12-22 18:15

    Invariant means something that should stick to its conditions no matter whatever changes or whoever uses/transforms it. That is to say, a property of a class always fulfills or satisfies some condition even after going through transformations by using public methods. So, the client or user of this class is ensured about the class and its property.

    For example,

    1. Condition on a function argument is that, it should always be > 0 (greater than zero) or should not be null.
    2. Minimum_account_balance property of an account class states, it cannot go below 100. So all public functions should respect this condition and ensure class invariant.
    3. Rule based dependency between variables, that is, the value of one variable depends on another, so if one changes, using some fix-rule, the other must also change. This relationship between 2 variables must be preserved. If it does not, then invariant is violated.

提交回复
热议问题