Friday, 13 November 2020

Abstraction function, representation invariant

Abstraction Function & Rep invariant

The abstraction functions map values in a class to the abstract concept's required values. The representation invariants are those values that satisfy the abstraction function. By asserting the abstraction function we create the link (abstraction) from ints and string to our concept. This can be seen as giving the class meaning.

The abstraction funtion is like a filter that only allows values past which correctly describe the abstract concept.
Figure 1 - RatNum ADT


Below ZeroNumber is the concept we want to create. We represent it with a float however the concept requires that it only represents the number 0. Therefore we assert the abstraction function on the inValue and discard any values which are not rep invariants, this results in our classes concept (of being zero) being enforced.

class ZeroNumber {
    ZeroNumber(float inValue) {
        assert(inValue == 0.0f);     (2. Assertion for rep invariants)
        value = inValue;
    float value;  (1. Representation)

The abstraction function here is that the ZeroNumber class must be a number that can only be 0.

The rep invariants here are all values of (inValue) that are 0.0f.  In order for abstration function to hold the assertion (2) must hold since only rep invariants are allowed.


  • Object-oriented Software Construction, 1st Edition Bertrand Meyer

No comments:

Post a comment

The difference between class and object.

 The difference between class and object is subtle and misunderstood frequently. It is important to understand the difference in order to wr...