javaoopmethodscontracts

When & how should constructors enforce limits on instance variables?


I'm new to programming and am learning Java as my first oo language, by working through Introduction to Programming Using Java by David J. Eck and reading forum posts when stuck.

My question could be considered a follow-up to Java Class Constructor Parameters with range limits which deals with limiting int arguments to an Hour class' constructor to 0 through 23.

The answers to the above question mentioned throwing either Instantiation Exception or IllegalArgumentException, but were unclear about which is better style.

Also, when, if ever, is the overhead associated with the validation code justified?


Solution

  • It is correct only to throw an IllegalArgumentException.

    Thrown to indicate that a method has been passed an illegal or inappropriate argument.

    An InstantiationException is for a different purpose.

    Thrown when an application tries to create an instance of a class using the newInstance method in class Class, but the specified class object cannot be instantiated. The instantiation can fail for a variety of reasons including but not limited to:

    • the class object represents an abstract class, an interface, an array class, a primitive type, or void

    • the class has no nullary constructor

    An InstantiationException has to do with a reflection call failing to call a constructor, but an IllegalArgumentException means that the constructor (or method) was called successfully, but the block of code determined that an argument was inappropriate.

    It is always best to have a little overhead to validate the arguments coming in to your constructor (and method). A program or class that isn't working properly is worse than a program that works properly and might be negligibly slower.