Class invariant

Class invariant
This article is about class invariants in computer programming, for use of the term in mathematics, see equivalence class and invariant.

In computer programming, specifically object-oriented programming, a class invariant is an invariant used to constrain objects of a class. Methods of the class should preserve the invariant. The class invariant constrains the state stored in the object.

Class invariants are established during construction and constantly maintained between calls to public methods. Temporary breaking of class invariance between private method calls is possible, although not encouraged.

An object invariant, or representation invariant, is a programming construct consisting of a set of invariant properties that remain uncompromised regardless of the state of the object. This ensures that the object will always meet predefined conditions, and that methods may, therefore, always reference the object without the risk of making inaccurate presumptions. Defining class invariants can help programmers and testers to catch more bugs during software testing.

Contents

Class invariants and inheritance

The useful effect of class invariants in object-oriented software is enhanced in the presence of inheritance. Class invariants are inherited, that is, "the invariants of all the parents of a class apply to the class itself."[1]

Inheritance can allow descendant classes to alter implementation data of parent classes, so it would be possible for a descendant class to change the state of instances in a way that made them invalid from the viewpoint of the parent class. The concern for this type of misbehaving descendant is one reason object-oriented software designers give for favoring composition over inheritance (i.e., inheritance breaks encapsulation).[2]

However, because class invariants are inherited, the class invariant for any particular class consists of any invariant assertions coded immediately on that class, logically "and-ed" with all the invariant clauses inherited from the class's parents. This means that even though descendant classes may have access to the implementation data of the their parents, the class invariant can prevent them from manipulating those data in any way that produces an invalid instance at runtime.

Programming language support

Assertions

Common programming languages like C++ and Java support assertions by default, which can be used to define class invariants. A common pattern to implement invariants in classes is for the constructor of the class to throw an exception if the invariant is not satisfied. Since methods preserve the invariants, they can assume the validity of the invariant and need not explicitly check for it.

Non-native support

For Java, there is a more powerful tool called Java Modeling Language that provides a more robust way of defining class invariants.

Native support

The class invariant is an essential component of design by contract. So, programming languages that provide full native support for design by contract, such as Eiffel and D, will also provide full support for class invariants.

Examples

Java

This is an example of a class invariant in the Java programming language with Java Modeling Language. The invariant must hold to be true after the constructor is finished and at the entry and exit of all public member functions. Public member functions should define precondition and postcondition to help ensure the class invariant.

public class Date {
    int /*@spec_public@*/ day;
    int /*@spec_public@*/ hour;
 
    /*@invariant 1<=day && day <=31; @*/ //class invariant
    /*@invariant 0<=hour && hour < 24; @*/ //class invariant
 
    /*@
    @requires 1<=d && d <=31;
    @requires 0<=h && h < 24;
    @*/
    public Date(int d, int h) { // constructor
        day = d;
        hour = h;
    }
 
    /*@
    @requires 1<=d && d <=31;
    @ensures day == d;
    @*/
    public void setDay(int d) {
        day = d;
    }
 
    /*@
    @requires 0<=h && h < 24;
    @ensures hour == h;
    @*/
    public void setHour(int h) {
        hour = h;
    }
}


D

D programming language has native support of class invariants, as well as other contract programming techniques. Here is an example from the official documentation.

class Date {
  int day;
  int hour;
 
  invariant() {
    assert(1 <= day && day <= 31);
    assert(0 <= hour && hour < 24);
  }
}

External links

See also

References

  1. ^ Meyer, Bertrand. Object-Oriented Software Construction, second edition, Prentice Hall, 1997, p. 570.
  2. ^ E. Gamma, R. Helm, R. Johnson, and J. Vlissides. Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley, Reading, Massachusetts, 1995., p. 20.

Wikimedia Foundation. 2010.

Игры ⚽ Поможем решить контрольную работу

Look at other dictionaries:

  • Invariant (computer science) — In computer science, a predicate that, if true, will remain true throughout a specific sequence of operations, is called (an) invariant to that sequence.UseAlthough computer programs are typically mainly specified in terms of what they change, it …   Wikipedia

  • Invariant estimator — In statistics, the concept of being an invariant estimator is a criterion that can be used to compare the properties of different estimators for the same quantity. It is a way of formalising the idea that an estimator should have certain… …   Wikipedia

  • Class (computer science) — In object oriented programming, a class is a programming language construct that is used as a blueprint to create objects. This blueprint includes attributes and methods that the created objects all share.More technically, a class is a cohesive… …   Wikipedia

  • Invariant (mathematics) — In mathematics, an invariant is a property of a class of mathematical objects that remains unchanged when transformations of a certain type are applied to the objects. The particular class of objects and type of transformations are usually… …   Wikipedia

  • Invariant chain — The invariant chain is a special polypeptide involved in the formation and deliverance of MHC class II protein.The nascent MHC class II protein in the rough ER has its peptide binding cleft blocked by the invariant chain (Ii; a trimer) to prevent …   Wikipedia

  • Invariant subspace — In mathematics, an invariant subspace of a linear mapping : T : V rarr; V from some vector space V to itself is a subspace W of V such that T ( W ) is contained in W . An invariant subspace of T is also said to be T invariant.If W is T invariant …   Wikipedia

  • Invariant basis number — In mathematics, the invariant basis number (IBN) property of a ring R is the property that all free modules over R are similarly well behaved as vector spaces, with respect to the uniqueness of their ranks. Definition A ring R has invariant basis …   Wikipedia

  • Invariant de classe — En programmation informatique, un invariant de classe est un invariant utilisé pour contraindre des objets d une classe. Pour chaque instanciation, l invariant est préservé avant et après l appel des méthodes de la classe. Liens externes (en) The …   Wikipédia en Français

  • Class automorphism — In mathematics, in the realm of group theory, a class automorphism is an automorphism of a group that sends each element to within its conjugacy class. The class automorphisms form a subgroup of the automorphism group. Some facts: Every inner… …   Wikipedia

  • Class function — In mathematics, especially in the fields of group theory and representation theory of groups, a class function is a function f on a group G, such that f is constant on the conjugacy classes of G. In other words, f is invariant under the… …   Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”