When & how should designers apply constraints on instance variables?

I am new to programming and learning Java as my first oo-language, working through David J. Ek's Introduction to Java Programming and reading forum posts when they get stuck.

My question can be seen as a continuation of the Parameters of the constructor of the Java class with range restrictions , which is devoted to limiting the internal arguments to the constructor of the Hour class to 0-23.

The answers to the question mentioned above concerned metadata of either ExceptionException or IllegalArgumentException, but it was not clear which one is better.

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

+4
source share
3 answers

It’s only right to throw it away IllegalArgumentException.

Thrown to indicate that the method was passed by an illegal or inappropriate argument.

InstantiationException for another purpose.

It is thrown when the application tries to create an instance of the class using the newInstance method in the class Class, but the specified class object cannot be created. Creating an instance may fail for a number of reasons, including but not limited to:

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

  • the class does not have a null constructor

An InstantiationException , , IllegalArgumentException , ( ) , , .

, , ( ). , , , , .

+4

, , , , , , , java.awt.Color @TNT .

, , , , .

, @rgettman ;-)

0

, , , , . , , . , , , , .

If you have a small package and a class that is used only in a limited context or even in a closed inner class, it will be more relaxed with respect to validation.

I would use an IllegalArgumentException or something derived from it for checking, because this type simplifies what happened and that the error is related to the caller.

0
source

All Articles