Can you advise on how to structure the problem proposed?

huangapple go评论61阅读模式
英文:

Can you advise on how to structure the problem proposed?

问题

我正在将一个旧的过程式算法改写为面向对象编程,我试图设计不同的类/对象。

该算法执行了一些函数/方法。
每个方法的输出将用作下一个方法的输入。
根据一些初始条件,有些函数可以被跳过。

所以假设我们有以下使用情况:

我开始考虑创建一个包含所有使用情况共有方法实现的抽象类,然后让子类实现不在抽象类中的方法。
然后在每个实现中有一个“execute”方法,根据使用情况调用不同的方法。
但我对这种方法不太满意,仍然存在重复。

您有什么建议吗?
提前感谢!

英文:

I'm re-working an old procedural algorithm in object oriented programming, and I'm trying to design the different classes/objects.

The algorithm is executing a couple of functions/methods.
The output of each method will be used as an input the following one.
Based on some initial condition, some functions can be skipped.

So let's say we have the following use cases:

FIRST SECOND THIRD FOURTH
initializeVariables() initializeVariables() initializeVariables() initializeVariables()
saveTemporaryData() saveTemporaryData() saveTemporaryData() saveTemporaryData()
addDataFromExternalSource() addDataFromDraft() addDataFromDraft() addDataFromPreviousVersion()
sortData() addDataFromExternalSource() addDataFromPreviousVersion() addDataFromExternalSource()
prepareOutput() sortData() addDataFromExternalSource() sortData()
prepareOutput() sortData() prepareOutput()
prepareOutput()

I started thinking to create an abstract class that contains the implementation of the methods that are common to all the use cases, and let subclasses implement the methods not in the abstract class.
And then have an "execute" method in each implementation that calls the different methods one by one based on the use case.
But I'm not satisfied of this approach, there's still repetition.

Do you have any suggestions?
Thanks in advance!

答案1

得分: 0

以下是翻译好的内容:

这并没有显示出有意的努力,感觉有点像在要求我们帮你做作业。尽管如此,根据给定的示例,您可以使用空值检查来确定是否应调用可选的方法,例如:

public class Example {
    Draft draft;
    void saveTemporaryData() {
        //TODO 逻辑
        if(draft != null) addDataFromDraft();
        addDataFromExternalSources();
    }

    void addDataFromDraft() {
        //TODO 逻辑
    }

    void addDataFromExternalSources() {
        //TODO 逻辑
    }
}
英文:

While this doesn’t show any intentional effort and feels a bit like you’re asking us to do homework for you. That being said, with the example given you can just use a null check to determine if optional methods should be called, such as:

public class Example {
    Draft draft;
    void saveTemporaryData() {
        //TODO logic
        if(draft != null) addDataFromDraft();
        addDataFromExternalSources();
    }

    void addDataFromDraft() {
        //TODO logic
    }

    void addDataFromExternalSources() {
        //TODO logic
    }

}

huangapple
  • 本文由 发表于 2023年2月23日 21:22:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75545440.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定