-1

I am trying to digest a large Java Application by modeling it in UML using ArgoUML. In the properties section of the UML diagramming tool there is a helpful checklist that I am assuming is used to help design good software. Most of the checklist items make sense except for 3.

1). Could you write an invariant for this class? 
2). Do all constructors establish the class invariant? 
3). Do all operations maintain the class invariant?

What is meant by these questions? I am new to object oriented design so an explanation would be helpful.

Thank you in advance.

Horse Voice
  • 7,218
  • 14
  • 56
  • 111
  • 4
    Have you Googled the term, "invariant"? Understanding of this appears to be the key to your question. – Hovercraft Full Of Eels Nov 06 '13 at 14:55
  • 1
    look at this: http://en.wikipedia.org/wiki/Class_invariant – tom Nov 06 '13 at 15:09
  • 1
    I can't understand why I keep getting down votes on this. I don't get invariants and what these questions are really asking. An explanation would help. I have googled it and have found that its something in your application that does not change and can be used as the control in writing your tests. Still, I don't know what these questions are really asking.. Constructors establish the class invariant? (what does this have to do with an unchanging condition?) Maintain the class invariant?? (What??) I need an example please. – Horse Voice Nov 06 '13 at 16:15

1 Answers1

2

To give an easy example: When you model a triangle, you want to make sure that the sum of the angles always adds up to 180 degrees.

class Triangle {
    number angle1, angle2, angle3;
}

This is the invariant (a condition that is supposed to be always true):

degrees (angle1 + angle2 + angle3) = degrees 180

Now the second question makes sense: since a constructor must make sure not to construct an object where the invariant doesn't hold.

The third question, then, asks if there are operations that could invalidate the invariant. For example:

    void setAngle1(number whatever) { angle1 = whatever; }

And here it turns out that the design above is not good. Why? Becasue there are redundant information. A better design would be this:

class Triangle {
    number angle1, angle2;   // two angles
    number side;             // and the connecting line
}

We can always compute angle3 from angle1 and angle2. And we just need to enforce the simpler invariant that angle1 + angle2 < 180° and side > 0

Ingo
  • 34,949
  • 5
  • 49
  • 97