(Subjective) Invalid Java Class Constructor

Viewed 82

I am programming a java class, where the given parameters could be invalid, but still be the right type. I want my class to take two integers, but the second one is not allowed to be zero. What do I have for possibilities to interrupt the Constructor, maybe returning manually null? What are my possibilities?

public class Test {
   private a, b;
   public Test(p1, p2) {
       if (p2 == 0) return null;
       a = p1;
       b = p2;
   }
}
3 Answers

A constructor doesn't have a return value, so returning null isn't an option. The idiomatic thing to do would be to throw an IllegalArgumentException:

public class Test {
   private a, b;
   public Test(p1, p2) {
       if (p2 == 0) {
           throw new IllegalArgumentException("p2 can't be null");
       }
       a = p1;
       b = p2;
   }
}

If you want to return null in the case of invalid parameters, you can't use a constructor.

Instead, make the constructor private, and write a static factory method:

private Test(int a, int b) {
  // Whatever.
}

public static Test create(int a, int b) {
  if (/* a and b are invalid */) {
    return null;
  }
  return new Test(a, b);
}

You then invoke Test.create instead of new Test.

This is only an option if you don't want to extend Test, though.

Quite a lot of possibilities, depending on what you need, which is the most important thing.

An idea could be throw an IllegalArgumentException if the 2nd parameter is 0 so the constructor exits with error and the class is not created.

Related