views:

174

answers:

2

I was just thinking of cases when invariant(s) for mainly classes, but to some extent also structs, cannot be readily defined. Would the lack of invariant(s) be a definitive sign of bad design of the class or struct, or can you see valid reasons not to be able to define them?

To me, it feels like that's where you end up when things are just thrown into a class, as if it would be a container, like an exploded data holder.

+4  A: 

Why can't they be readily defined? It does seem like if the person writing the class can't express an invariant for it, it's bad design.

Of course, there are classes that have no invariants. If it is simply intended to hold a couple of unrelated values, like a tuple, with no actual behavior defined, then anything you do with the class is valid, and there are no invariants it needs to maintain. (other than trivial ones like "it'll contain whatever you put in it"

But that's different from "I can't tell you what the invariants are". The latter seems like a serious problem. If you can't define an invariant for a class, you are basically saying that you don't know how it behaves. That makes it rather useless, I'd say.

jalf
+2  A: 

You don't necessarily need (non-trivial) invariants for a well designed class. It really all depends on what sort of object that the class is meant to represent.

Really, you don't even need to know what an invariant is to design a class well... and a well designed class doesn't even have to follow OO design principles at all... it all depends on what you mean by "well designed".

jheriko