Is there a name for this API/type design principle? (I think of it as “state hygiene”)

  softwareengineering

When designing types and their APIs, I try to adhere to these simple principles (which vaguely feel like one general principle to me) as much as feasible:

  • There is a one-to-one correspondence between possible states/values of the type (combinations of possible property values, etc.) and their domain interpretations. So there are no invalid states, and also no redundant states that mean the exact same thing as other states.

(A common violation is when there’s a type with some boolean property HasFoo, and two optional properties Foo and Bar where Foo is only meaningful when HasFoo is true, and Bar only when HasFoo is false. If this isn’t enforced by the type system, Foo and Bar can both be set at once — redundant states; or neither or the wrong one can be set — invalid states.)

  • An instance of the type is valid as soon as it is constructed; all methods and properties are valid to call or access at any time, and can be called in any order, with consistent semantics.

(e.g., .NET’s IEnumerator<T> expresses iteration via MoveNext() and Current members, where you need to call MoveNext() and have it return true before Current is valid to access; Rust’s Iterator trait has a better API, with a single next() method which returns an Option<T>, so calling it is always valid and it just returns Nothing once the iteration is exhausted.)

I think of this principle as “state hygiene,” and it seems pretty important and basic to me, but I’m not sure I’ve ever quite seen it spelled out anywhere in all the reading about programming I’ve done, though it no doubt overlaps with other common concepts (e.g., database normalization). Also, I feel like much language and API design really hasn’t been too conscious of this until recently. For example, a language feature that often really helps with state hygiene — including in both of the examples I gave here ― is sum types/discriminated unions, and their special case of optional nullability or an Option type. But up till 2014 or so those were treated as exotic features by the mainstream, and they’re just now starting to make it in to languages like C#.

So my question is: is there a better name for this principle? Or how would you characterize it?

New contributor

suushikijitsu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT