Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

condition based lombok building of objects

So here is the existing code snippet written to build Humans ( as in matrix movie :) )

if (gender.equals("male")){
    return Human.builder()
        .gender('male')
        .name('abc')
        .speaks("english")
        .alive(true)
        .build();
}else{
    return Human.builder()
        .gender('female')
        .name('abcd')
        .speaks("english")
        .alive(true)
        .build();    
}

If you look, this code has lot of redundancy in attribute assignment which can be minimised. Now imagine 10 conditions like it (here, its just 2!), no matter what you try, it would eventually lead to ugly looking redundant code.

I tried searching lot of resources online and couldn't find any way to build object as per builder design. What i would like to achive here ( to reduce code redundancy) is something like below :

Human human = Human.builder()
            .speaks("english")
            .alive(true);

if (gender.equals("male")){
        human = human    // or just human.gender('male').name('abc'); no assignment
        .gender('male')
        .name('abc');
}else{
        human = human // or just human.gender('female').name('abcd'); no assignment
        .gender('female')
        .name('abcd');
}            
return human.build();

Is this possible via lombok or anyone knows a better way to build objects here?
If its worth it, i am on drop-wizard

like image 599
NoobEditor Avatar asked Jan 29 '23 18:01

NoobEditor


1 Answers

Use Lombok's Builder:

import lombok.Builder;
import lombok.ToString;

@Builder
@ToString
public class Human {
    private String name;
    private String gender;
    private String speaks;
    private boolean alive;


    public static void main(String[] args) {
        HumanBuilder humanBuilder = Human.builder();

        String gender = "female";


        humanBuilder
                .speaks("english")
                .alive(true);

        if("male".equals(gender)){
            humanBuilder
                    .gender("male")
                    .name("abc");
        }else{
            humanBuilder
                    .gender("female")
                    .name("abcd");
        }

        Human human = humanBuilder.build();
        System.out.println(human);
    }
}

Result:

Human(name=abcd, gender=female, speaks=english, alive=true)
like image 174
Dmitry Gorkovets Avatar answered Jan 31 '23 08:01

Dmitry Gorkovets