Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I validate a copy constructor's parameter?

public class Rectangle {

  int width, height;

  public Rectangle(int width, int height) {
    this.width = width;
    this.height = height;
  }

  public Rectangle(Rectangle source) {
    this(source.width, source.height);
  } 
}

Let's say I have a class with multiple constructors, one of which is a copy-constructor (to copy an object).

Is there any way I can make check if source is null in the copy-constructor and throw an IllegalArgumentException if it is? Because the other constructor call has to be the first statement in my constructor.

like image 515
helll7 Avatar asked Sep 05 '25 17:09

helll7


1 Answers

You could introduce a private static method that returns the relevant value with a null check to throw the IllegalArgumentException (in this case the width as it's the first parameter on the same object).

For example:

public class Rectangle {

    private int width, height;

    public Rectangle(int width, int height) {
        this.width = width;
        this.height = height;
    }

    public Rectangle(Rectangle rectangle) {
        this(getWidth(rectangle), rectangle.height);
    }

    private static int getWidth(Rectangle rectangle) {
        if (rectangle == null) {
            throw new IllegalArgumentException("null value");
        }
        return rectangle.width;
    }

}

Reflecting on the comment to the question above, why not NullPointerException?

This question: IllegalArgumentException or NullPointerException for a null parameter? has some good discussion points. But I'm inclined to agree with the sentiments of "Effective Java" that NullPointerException should be preferred as cited in this answer to that very question.

"Arguably, all erroneous method invocations boil down to an illegal argument or illegal state, but other exceptions are standardly used for certain kinds of illegal arguments and states. If a caller passes null in some parameter for which null values are prohibited, convention dictates that NullPointerException be thrown rather than IllegalArgumentException."

like image 79
d.j.brown Avatar answered Sep 09 '25 04:09

d.j.brown