0

I have a situation where I have to copy values from one object to another. For each field the copy statement is wrapped with the following snipped of boilerplate code:

if (a.getC() != null) {
   b.setC(a.getC());
}

I had a look at Guava Precondition.checkNotNull(...) but it still throws NPE which I'm trying to evade.

How can I do that in a more natural way?

Harmlezz
  • 7,972
  • 27
  • 35
user2508615
  • 213
  • 2
  • 16

3 Answers3

1

Apache commons-lang3 offers this:

b.setC(ObjectUtils.defaultIfNull(a.getC(), b.getC()));

But I have to admit that I'm not sure if this would really be an improvement.

Ray
  • 3,084
  • 2
  • 19
  • 27
1

You could make a method using var args that checks all the args for your if statement:

public boolean argsNotNull(Object ... objs) {
    boolean b = true;
    for(Object o : objs) {
        if(o == null) {
            b = false;
            break;
        }
    }
    return b;
}

Then use it like this:

if(argsNotNull(a)) {
    Object c = a.getC();
    if(argsNotNull(b, c)) { // A null 'c' object may be valid here, depends on your logic
        b.setC(c);
    }
}

Since this method uses var args you can feed it as many args as you want, but it will not work with primitives in its current state.

ubiquibacon
  • 10,451
  • 28
  • 109
  • 179
  • This doesn't really solve the problem of `null` checking. It just delegates it to a different method. – Jeffrey Apr 02 '14 at 13:16
  • @Jeffrey OP asked for more natural. This isn't as nice as say the Groovy [safe navigation operator](http://groovy.codehaus.org/Operators#Operators-SafeNavigationOperator(?.)), but it is better than the alternative of (`a != null && b != null && c != null`) or vast, non-specific try/catch blocks. – ubiquibacon Apr 02 '14 at 13:34
0

Is the b.C value supposed to exactly reflect what is in a.C ? In that case if a.C is null then b.C whould be null, and you don't really need a null check.

Otherwise, to avoid curley braces you could do something like this :

b.setC((a.getC() == null) ? b.getC() : a.getC());

This assumes that the getter and setter from b match up exactly. If C from a is null then setC() from getC() which effectively does nothing.

Oliver Watkins
  • 12,575
  • 33
  • 119
  • 225