Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>That example in the Wiki is implementing invariants with JML, which is a very specific, exotic and perhaps well-thought-out research technology, but it isn't necessary mainstream at all. Also its not just talking about invariants but just talking about asserting a mutator did what was expected, which isn't what I think of when I think of invariants. I haven't read Coders at Work but I doubt anyone in Coders at Work used JML.</p> <p>Anyway, I always thought invariants were a great way to "crash early" and keep your code from trying to do reasonable things when in fact the program state is in an unreasonable (unplanned-for) state.</p> <p>A good example of an invariant in C# code might be to never give an object to N-Hibernate for saving unless that object has passed on its invariants, of which there should be many in order to prevent non-sensical data from entering the database. Let's see if I can think of any other examples...</p> <ul> <li><p>Suppose you have a User class that is always supposed to have a primary email address property, then an invariant to check before Saving might be to make sure the email address field isn't empty. Otherwise, other application logic down the road that assumes email addresses exist for all users might mess up when trying to send a User an email later.</p></li> <li><p>Suppose further that a User object "has many" Email objects, and suppose that it doesn't make any sense for an Email to exist without an owning user, then an invariant on the Email class might be to make sure the Email's reference to its user is always not null, otherwise you have an orphan Email object which could result in null pointer exceptions when you try to refer to the email's owner.</p></li> <li><p>Suppose you're writing a GUI that is supposed to present the status of an Amazon S3 object in a conventional WPF form. An invariant on the form might be to make sure that the form is properly bound to its object before executing any event handlers on that form.</p></li> <li><p>Suppose you're writing StackOverflow. An invariant here might be to make sure a user's reputation level is never negative, even if the user is taking reputation penalties. Negative reputation might break those pretty graphs that render experience as a function of time (unless those graphs are prepared to chart lines below the 0 y-axis, which they very may well be...).</p></li> </ul> <p>As for when to check for invariants, you could do this at the end of any method that mutates data state. At the most aggressive and paranoid level of defensive programming, you could check an invariant before and after all methods.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload