-3

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?

closed as off-topic by gnat, Jörg W Mittag, Andres F., Laiv, Bart van Ingen Schenau Nov 29 '18 at 11:49

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions asking for assistance in explaining, writing or debugging code are off-topic here. These can be asked on Stack Overflow if they include the desired behavior, a specific problem or error, and the shortest code necessary to reproduce it in the question (see Minimal, Complete, and Verifiable Example)." – gnat, Jörg W Mittag, Laiv
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 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 – Broman Nov 26 '18 at 21:44
4

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.