简体   繁体   English

如何重构else-如果选择正确的构造函数

[英]How to refactor else-if for choosing right constructor

I'm on the way to implement Factory pattern in my app and work going fine except block of code below (i have another one, much larger for another class). 我正在我的应用程序中实现Factory模式,除下面的代码块(我还有一个,对于另一个类来说,它要大得多)之外,其他代码工作正常。 Is there any way to refactor this "jungle"-structure? 有什么方法可以重构这种“丛林”结构? Thanks in advance! 提前致谢!

private Goal createLocalTaskInstance(HashMap<String, Object> goalDetails){
    Goal goal = null;

    if (goalDetails.get("description") == null &&
            goalDetails.get("endDate") == null){
        goal = new Task(String.valueOf(goalDetails.get("title")));

    } else if (goalDetails.get("description") != null &&
            goalDetails.get("endDate") == null) {
        goal = new Task(String.valueOf(goalDetails.get("title")),
                String.valueOf(goalDetails.get("description")));

    } else if (goalDetails.get("description") == null &&
            goalDetails.get("endDate") != null) {
        goal = new Task(String.valueOf(goalDetails.get("title")),
                        (Date) goalDetails.get("endDate"));

    } else if (goalDetails.get("description") != null &&
            goalDetails.get("endDate") != null){
        goal = new Task(String.valueOf(goalDetails.get("title")),
                String.valueOf(goalDetails.get("description")),
                (Date) goalDetails.get("endDate"));
    }
    return goal;
}

I would suggest that you simply call the default constructor (with all three arguments) regardless of some of them being null, and then simply do a null check in the constructor. 我建议您简单地调用默认构造函数(具有所有三个参数),而不管其中某些参数是否为null,然后在构造函数中执行null检查。 It would then look something like this: 然后看起来像这样:

goal = new Task(String.valueOf(goalDetails.get("title"),
                goalDetails.get("description"), 
                goalDetails.get("endDate"));

And the Task class: 和Task类:

public class Task {
    private String title;
    private String description;
    private Date endDate;

    public Task(String title, String description, Date endDate) {
        this.title = title;
        if(description != null) {
            this.description = description;
        }
        if(endDate != null) {
            this.endDate = endDate;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM