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!
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
}
}