Note that there are some explanatory texts on larger screens.

plurals
  1. POIs IllegalStateException appropriate for an immutable object?
    primarykey
    data
    text
    <p>Would you throw an <code>IllegalStateException</code> if:</p> <ol> <li>A method is unable to do its job because of the value(s) of one or more fields</li> <li>Those fields are <code>final</code> and assigned only in the constructor?</li> </ol> <p>Textbook example: your class is an immutable <code>Collection&lt;BigInteger&gt;</code> and your method is supposed to return the maximum element, but this instance is empty.</p> <p>I have read <a href="http://smallwig.blogspot.com/2008/06/common-java-unchecked-exception-types.html" rel="nofollow noreferrer">Kevin Bourillon`s blog post</a> on the subject and I am not sure which rule applies.</p> <blockquote> <p>UnsupportedOperationException - this means that the method invoked will always fail for an instance of this class (concrete type), regardless of how the instance was constructed.</p> </blockquote> <p>Definitely not. Many instances of this class are not empty and the operation would have succeeded.</p> <blockquote> <p>IllegalStateException - ... there does exist at least one alternate state that the instance in question could have been in, which would have passed the check ... &lt;snip&gt; ... Note also that this exception is appropriate whether or not it is possible to actually mutate this aspect of the instance's state, or it's already too late.</p> </blockquote> <p>Not quite. This instance was constructed with zero length, so <em>this instance</em> is not and could never have been non-empty.</p> <blockquote> <p>IllegalArgumentException - throwing this exception implies that there exists at least one other value for this parameter that would have caused the check in question to pass.</p> </blockquote> <p>Might apply if the parameter in question is the implicit <code>this</code> parameter. This is the exception I am tempted to throw, but I am concerned that it could be confusing.</p> <hr> <p><strong>Update</strong>: changed example from <code>Collection&lt;Integer&gt;</code> to <code>Collection&lt;BigInteger&gt;</code> because the fact that there was an identity element (<code>Integer.MIN_VALUE</code>) distracts from the question.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload