javaif-statementnull-check

Java reduce cognitive complexity of method which has multiple if statements


Hello I am looking for a way to reduce cognitive complexity of method which has multiple if statements. All are basically nullchecks for each item of object and is required.

Code snippet:

private void assignFruit(FruitBasket1<?> fruit1, FruitBasket2 fruit2) {
        
        if (fruit1.name != null) {
            fruit2.setName(fruit1.name.toString());
        }

        if (fruit1.number != null) {
            fruit2.setNumber(fruit1.number.toString());
        }

        if (fruit1.color != null) {
            fruit2.setColor(fruit1.color.toString());
        }

        if (fruit1.region != null) {
            fruit2.setRegion(fruit1.region.toString());
        }
        
}

I have tried to use switch case but since its only null check didnt find feasible, also tried ternary operator. Is there a simpler way to do this as although in the code snippet its only few fields there are almost 20 fields which need be null checked. What are the other possibilities to do this simple manner without modifying the POJO class and managing in this method itself.

Note: There was an error in the code in the way values are set


Solution

  • You can use Optional<>.

    // static imported Optional.ofNullable()
    private void assignFruit(FruitBasket1<?> fruit1, FruitBasket2 fruit2) {
       ofNullable(fruit1.name).ifPresent(fruit2::setName);
       ofNullable(fruit1.number).ifPresent(fruit2::setNumber);
       ofNullable(fruit1.color).ifPresent(fruit2::setColor);
       ofNullable(fruit1.region).ifPresent(fruit2::setRegion);
    }
    

    You can improve it a little bit more with a static import of ofNullable().

    Edit

    I'm not sure, but you need to change the type somehow?
    Also that is fluent possible with Optional.

    // static imported Optional.ofNullable()
    private void assignFruit(FruitBasket1<?> fruit1, FruitBasket2 fruit2) {
       ofNullable(fruit1.name).map(Object::toString).ifPresent(fruit2::setName);
       ofNullable(fruit1.number).map(Object::toString).ifPresent(fruit2::setNumber);
       ofNullable(fruit1.color).map(Object::toString).ifPresent(fruit2::setColor);
       ofNullable(fruit1.region).map(Object::toString).ifPresent(fruit2::setRegion);
    }