The established practice to check method parameters can be generalized to check correct usage of a class. In the given example it is illegal to call method doSomething()
when the instance variable root
has not yet been initialized.
If you want a best practice rule, it is not to generally check instance variables, but to check that a certain usage protocol of a class is obeyed. (Unless the class is written in a way that no particular protocol needs to be followed, which is usually the better option.) This check will of course typically involve checking instance variables.
In contrast to throwing an IllegalArgumentException
after a negative method parameter check, a protocol violation should lead to an IllegalStateException
.
In the given example an IllegalStateException
should be thrown, because that instance is not in a state where doSomething()
may be called.