There are always things that can be improved in a book. This page contains my thoughts on what I would have written differently or added to it.
In our minds, we should separate between the concrete implementation of the pre- and post-conditions from the intention. Take the
toCamelCase method from the Apache Commons as an example. It receives a
str as parameter, and it doesn’t define any pre-conditions to it. Meaning, it accepts any strings, even null and empty. The first line of the method’s implementation is something like
if(str==null) return str;. This line is there to make sure the method can handle the null case, given that it has no pre-conditions. If we now talk about implementation, this line in itself is not a pre-condition check. The developer could have opted for a stronger pre-condition, e.g.,
str can’t be null. In this case, the first line of this method would probably be
if(str==null) throw new RuntimeException(), or
assert str != null. In these examples, these lines are pre-conditions checks.
Can static methods have invariants? My answer in the book is ‘no’. My colleague Frank Mulder, however, noted that when we talk about “class invariants”, we normally mean “object invariants”, so conditions that hold for the state of an object throughout its lifetime. In that sence, static methods do not check for class/object invariants, because they do not belong to any object. However, as classes can have static attributes, you could define conditions that concern those attributes, and check for them inside your static methods. I agree with it!