gpt4 book ai didi

java - 重构基于 boolean 的流程

转载 作者:行者123 更新时间:2023-12-02 03:16:59 25 4
gpt4 key购买 nike

我们的应用程序是围绕一个Context类构建的,该类具有许多原始字段和 boolean 值上下文在几乎所有流程中传递,并根据 boolean 标志做出决策。现在,为了实现新功能,一个新的 boolean 值被添加到上下文中,并且必须在 10 个不同的位置进行检查。总体流程的结构与此示例类似。

public void handle(context) {
if (context.isBig())
drawBigThing(context)
else
drawSmallThing(context)
//more code
...... handleColor(context) //somewhere deeper in the flow/stack

}

private void handleColor(context) {
if (context.isBig())
takeMoreColor(context.getColor())
else
takeLessColor(context.getColor())
}

正如您在代码的不同部分中看到的那样,我们回顾相同的标志,但根据它做出不同的决定。现在,如果我添加 context.isVeryBig(),您可以看到它会如何爆炸。

(在 java 8 工具上)有哪些想法可以重构从具有不同职责但仍对同一标志感兴趣的方法/类查询的 boolean 标志?

一个想法是让上下文变得更智能,不是持有 boolean 标志,而是为每个职责保留一个状态/策略,但这会泄漏上下文中的职责(也许它们可以以某种方式解耦?),我仍然会有IF,但至少它们会在流程开始之前分组到一个位置

最佳答案

这是一个概念性问题。所以,也许我没有完全回答这个问题。

One idea would be to make the context smarter, not hold boolean flags but a State/Strategy for each of the responsibilities, but this leaks the responsibilities in the context (maybe somehow they can be decoupled?)

使用策略似乎是个好主意。尽管如此,我不会把上下文讲得太巧妙。上下文应包含数据或名称具有误导性及其责任。

您想知道上下文和处理是否可以解耦。你可以,而且我认为应该这样做。

i will still have the IFs but at least they will be grouped in one place and before the flow starts

我同意。为什么不在工厂类中以便通过契约进行通信并在返回的实现中更加灵活。

我向您建议两种解决该问题的方法。

1)灵活处理,全面实现混凝土搬运工搬运

界面:

public interface FlowHandler{

void handle(Context context);
}

并根据需要实现(根据您的 boolean 值,这使得流程的行为发生变化):

public class  BigFlowHandler implements FlowHandler {

public void handle(Context context){
drawBigThing(context);
takeMoreColor(context.getColor())
}
}

该设计非常灵活,因为它允许每个实现按照自己的意愿处理问题。

尽管如此,如果所有处理程序的操作应具有相同的性质并以相同的顺序执行,则可以使用另一种设计来插入这个方向。

2) 一个预定义的流程,它限制处理步骤并分解步骤的处理

您可以通过在具体类 (FlowHandler) 中声明具体方法 (handle(Context context) 来实现此目的,该方法会链接任何已执行流所需的操作。操作依赖于策略实现的工厂方法。
具体类(FlowHandler)回答“什么”问题(流程的步骤及其顺序),第二个答案回答“如何”(流程步骤的实现)

public interface HandlerOperations{
drawThing(Context context);
takeColor(Context context);
}

public class FlowHandler{

public FlowHandler(HandlerOperations handlerOperations){
this.handlerOperations = handlerOperations;
}

public void handle(Context context){
handlerOperations.drawThing(context);
handlerOperations.takeColor(context);
}
}

关于java - 重构基于 boolean 的流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40162672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com