tags:

views:

151

answers:

3

I am taking an intermediate programming course which stresses the use of invariants. I have never used them before and they seem to take up more time to create. Does the software engineering industry stress the use of invariants?

+5  A: 

I don't think about invariants very much - not as much as pre/post-conditions. I should probably think about invariants more, to be honest.

One thing to think about is immutability - if you're using an OO language but make types immutable where you can, you don't need to worry about invariants as much: if the state is valid to start with, it will stay valid.

It does sound like your course may be over-emphasizing invariants a little bit... but it does depend on what you're doing. They're more appropriate in some situations than others. Maybe your lecturer is just a big fan of them with a lot of experience in areas where they're really useful.

Jon Skeet
+6  A: 

Depends on who you ask - I use invariants simply because it makes life easier. Learning invariants is like learning blind-typing. Each time you use an invariant, you know more about your code. If you insert the invariant as a comment in your loop, it helps the reader A LOT. I would say that using invariants makes creation and maintenance of source code much cheaper, and makes you able to create much more sophisticated algorithms, which are still maintainable.

And in contrast to OOP, I have never experienced anyone wasting their time by using invariants.

Lars D
A: 

Once you learn what invariants are and what they mean, it tends to change the way you reason about code. I mean, I very seldom write explicit invariants. But I often have a picture in my mind of the invariant in the code I'm writing. This leads you to write code that is much simpler. In most cases you end up with code that is so simple that you don't need to write an explicit comment about the invariant. Yet people who don't know about invariants write code that is much more complicated :)

xpmatteo