Search code examples
javaexceptionassert

What exception to use to prevent a method from being called multiple times?


I have a method that should only be called once during an object's lifetime. In order to ensure that this is the case, the method sets a boolean flag in the Object to true so it can later check if this method has already run. I am currently throwing an IllegalArgumentException (with a descriptive message) if this method is called a second time during a single object's lifetime, but that doesn't feel quite right to me, since the problem is not actually with the arguments themselves. Is there a better exception to use than an IllegalArgumentException?

I chose not to use an assert statement in this case, because the class and method are both visible outside the package, so the problem may be caused by code outside of my package. Is that correct thinking?


Solution

  • Throw an IllegalStateException.

    But since exceptions shouldn't be part of the ordinary control flow, you should add a companion method, which returns a boolean that indicates whether the next call to the method will be successful.

    An example for such a companion method is Iterator#hasNext().

    A well-designed API must not force its clients to use exceptions for ordinary control flow. A class with a “state-dependent” method that can be invoked only under certain unpredictable conditions should generally have a separate “state-testing” method indicating whether it is appropriate to invoke the state-dependent method. For example, the Iterator interface has the state-dependent method next and the corresponding state-testing method hasNext.1

    1: from Effective Java, Chapter 9: Exceptions