-2

I want a class A, and I want the relation that A can have zero or one X.

So I wrote this class:

public class A {
    private X x = null;

    public A() {}
    public A(X x) { this.x = x; }

    public boolean hasX() { 
       if(x==null) 
          return false; 
       return true; 
    }
    public void setX(X x) { this.x = x; }
    public X getX() { return x; }
}

But I get the feeling that I have got something wrong here. From what I have heard, you should avoid using null like this. But I am not sure how to do it. Is this the correct or recommended way to handle this?

2
  • Can't you define x as a X[1]?
    – A.Rashad
    Nov 26 '18 at 21:41
  • @A.Rashad I guess I could, but it feels very workaroundish
    – klutt
    Nov 26 '18 at 21:44
5

As of Java 8, this is best handled via the Optional type:

public class A {
    private Optional<X> x = Optional.empty();

    public A() {}
    public A(X x) { this.x = Optional.of(x); }

    public void setX(X x) { this.x = Optional.ofNullable(x); }
    public Optional<X> getX() { return x; }
}

The use of Optional.ofNullable(...) means that the value can be "unset" (to empty).

3

Alternately always have one. Use a Null Object.

ie.

class NullX extends/implements X
{
    //implement with noops
}

Now always assign the value an object. This has the advantage of obviating any null, or has a checks. It is a variable, it isn't null, and it can be interacted with without surprise.

Obviously this NullX must implement the interface and the expectations correctly. This does preclude some interfaces from having a null implementation, and may even make several null implementations possible.

Not the answer you're looking for? Browse other questions tagged or ask your own question.