Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: changed the example and reworded the description a bit

Java classes and methods may have invariants.  An invariant is a property that is assumed to be true at certain points during program execution, but not formally specified. They may be used in assert statements, or informally specified in comments.

Method invariants can include Many methods offer invariants, which can be any or all of the guarantees made about what the method can do, requirements about the required state of the object when the method is invoked, or guarantees about the state of the object when the method completes. For example, the % operator, which computes the remainder of a number, provides the invariant that

0 <= abs(a % b) < abs(b), for all integers a, b where b != 0

a method of a Date class might guarantee that 1 <= day_of_month <= 31 when the method exits.  

Class invariants Many classes also offer invariants, which are guarantees made about the state of their objects' fields upon the completion of any of their methods. For example, classes whose member fields may not be modified once they have assumed a value are called immutable classes. An important consequence of immutability is that the invariants of instances of these classes are preserved throughout their lifetimes.

Similarly, classes can rely on invariants to properly implement their public interfaces. These invariants might relate to the state of member fields or the implementation of member methods. Generally, classes can rely on encapsulation to help maintain these invariants, for example, by making member fields private. However, encapsulation can be incompatible with extensibility. For example, a class designer might want a method to be publicly accessible, yet rely on the particulars of its implementation when using it in another method within the class. In this case, overriding the method in a subclass can break the internal invariants of the class.Therefore, extensibility   Extensibility consequently carries with it two significant risks: a subclass can fail to satisfy the invariants promised to clients by its superclass, and it can break the internal invariants on which the superclass relies. For instanceexample, an immutable class that lacks the final qualifier can be extended by a malicious subclass that can modify the state of the supposedly immutable object. Furthermore, a malicious subclass object can impersonate the immutable object while actually remaining mutable. Such malicious subclasses can violate program invariants on which clients depend, consequently introducing security vulnerabilities. Note that the same can be said for a benign subclass which mistakenly supports mutability. The risks above relate to both benign and malicious development.

...