-1

Let there be a class A. Class B is as follows:

public class B {

    private int anInt;
    private String aString;
    ...

    public B(A initObj) {
       anInt = initObj.getIntField();
       aString = initObj.getStringField();
       ...
    }

    ...
}

If initObj is null, then what makes the most sense is for the B object to be null also. But, according to the internet, a Java constructor cannot return a null.

Obviously, it is best to check on the side of the code that is calling the constructor for B so as not to call the constructor with a null argument. But, assuming that this possibility occurs, what is the best way to gracefully handle this situation.

What is the best way to handle a situation where B is initialized with null?

kingledion
  • 2,263
  • 3
  • 25
  • 39
  • you can include a check inside the constructor for B like --> `if(initObj!=null){//your initialization code}` so that you know that argument with null is taken care of – mettleap Oct 28 '18 at 01:42
  • @mettleap So that was my first thought, but then I realized i had this dummy object with no data in it at all masquerading as a real object, just waiting to break something downstream. I realized I'd rather just throw an exception at that point. – kingledion Oct 28 '18 at 01:50
  • 1
    maybe a factory pattern? something like B.getNewInstance(initObj); which will return either null if initObj is null or an instantiated B if initObj is valid? – Angel Koh Oct 28 '18 at 02:17
  • 2
    throw an `Exception`, the faster the better. guava "invented" these `Preconditions` in java I think, and jdk uses it via `Object::requireNonNull` and the like – Eugene Oct 28 '18 at 02:54

1 Answers1

0

You have a couple of options depending on what you want to happen in your application. You could change the signature of B constructor to take the int and String parameters instead of A. This way the caller has to deal with a possibly null initObj and B does not have to deal with potentially null arguments in the constructor. The constructor could also perform a null check on initObj and either don't initialize the fields of B if that is a valid state for B, or throw an exception if this is really invalid.

John Camerin
  • 677
  • 5
  • 15