Opal
Opal

Reputation: 1057

How should I wrap an object that is from an unknown source

I have an application with a number of interface implementations with an unknown source. I wanted to clean up my source code so that I do not need to write:

A a = AFactory.getImpl();
B b = a.getB();
if(b == null) return;
b.doSomething();

Which becomes very long winded. Should I wrap this object so that A will never return null from getB(); and if that is a good idea, how should I do that, Should I provide an implementation that throws an error like InvalidImplemetationException and force it to be caught.

Upvotes: 0

Views: 121

Answers (2)

TimK
TimK

Reputation: 4835

You should consider using the Null Object Pattern: define a value of B that encapsulates the behaviour you want when you don't really have a B. In this case that means doSomething() does nothing.

B would look like this:

public class B {
    public static final B NULL = new B() {
        public void doSomething() {
        }
    };

    public static B fromA(A a) {
        B b = a.getB();
        return b == null ? NULL : b;
    }

    public void doSomething() {
        ...
    }
}

You would use it like this:

A a = AFactory.getImpl();
B.fromA(a).doSomething();

If you can change AFactory.getImpl, have it return B.NULL instead of null. Then you don't need B.fromA and you can do this instead:

A a = AFactory.getImpl();
a.getB().doSomething();

Upvotes: 1

BrainStone
BrainStone

Reputation: 3195

In this case I would recommend you putting the b == null code in the getB function.

It really seems that you did some research and picked a very good exception.

A good alternative is instead of throwing an exception returning a new object of B.

Upvotes: 0

Related Questions