基于条件的lombok对象构建

问题描述 投票:0回答:3

所以这是为构建

Human
而编写的现有代码片段(如
matrix
电影:))

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();    
}

如果你看一下,这段代码在属性分配中有很多冗余,可以最小化。现在想象 10 个这样的条件(这里只有 2 个!),无论你尝试什么,最终都会导致看起来丑陋的冗余代码。

我尝试在网上搜索大量资源,但找不到任何按照构建器设计构建对象的方法。我想在这里实现的目标(减少代码冗余)如下所示: 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();

这可以通过 lombok 实现吗?或者有人知道在这里构建
对象的更好方法吗?

如果值得的话,我就drop-wizard

	

使用Lombok的Builder:
java dropwizard builder lombok
3个回答
7
投票
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); } }

结果:

Human(name=abcd, gender=female, speaks=english, alive=true)

您可以使用以下任何一种方法来消除代码冗余并保持清晰:

4
投票
选项 1:

Human human = Human.builder() .gender(gender.equals("M")?"male":(gender.equals("F")?"female":"transgender")) .name("abc") .speaks("english") .alive(true) .address(Optional.ofNullable(address).orElse(defaultAddress)) .build();

选项 2:

Human human = Human.builder() .gender(getGender(gender)) .name("abc") .speaks("english") .alive(true) .address(Optional.ofNullable(address).orElse(defaultAddress)) .build(); public static String getGender(String gender){ return gender.equals("M")?"male":(gender.equals("F")?"female":"transgender"); }

选项 3:

Human.HumanBuilder humanBuilder = Human.builder(); humanBuilder.name("abc").speaks("english").alive(true); if(gender.equals("M")){ humanBuilder.gender("male"); }else { humanBuilder.gender("female"); } Human human = humanBuilder.build();

我的
个人偏好

选项2,因为它使代码更更干净 希望这有帮助。

我喜欢这种模式 - 它允许跳过不存在的值(例如未明确给出):

0
投票
Human human = Human.builder() .name("abc") .speaks("english") .alive(true) .address(Optional.ofNullable(address).orElse(defaultAddress)); getGender() .ifPresent(gender -> human.gender(gender)); human.build(); ... public static Optional<String> getGender(String gender){ return gender.equals("M")?"male": (gender.equals("F")?"female":"transgender"); }


© www.soinside.com 2019 - 2024. All rights reserved.