Brian Slesinsky's Weblog

Sunday, 12 Oct 2003

Stroustrup on Class Invariants

In an interview on Artima, Bjarne Stroustrup has this to say about classes and invariants:

"What is it that makes the object a valid object? An invariant allows you to say when the object's representation [is] good and when it isn't. [...] So you have to be able to state which objects make sense. Which are good and which are bad. And you can write the interfaces so that they maintain that invariant."

And not everything is an object:

"If every data can have any value, then it doesn't make much sense to have a class. Take a single data structure that has a name and an address. Any string is a good name, and any string is a good address. If that's what it is, it's a structure. Just call it a struct. Don't have anything private."

And where are invariants established? In the constructor:

"The way the whole thing is conceived is that the constructor establishes the environment for the member functions to operate in, in other words, the constructor establishes the invariant."

I think this confirms that my Struct Argument pattern is on the right track, and Half-Beans were half-baked. (In fact, the whole idea of a JavaBean is somewhat suspect.) Nice to find someone who agrees with me, even if it's in C++.

On the other hand, I'm not so sure about his preference for making convenience methods static. The trouble with static methods in Java is that people forget to use them, especially if they're in another class (DateUtils rather than Date.) What tends to happen is that you end up with multiple utility methods with duplicate code. Putting them on the base class is more convenient for the API user, even if it's not as clean for the implementer.