Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force object to run/execute methods in sequence

I have a class which takes multiple collections, and then needs to perform calculations on these collections in a particular order. E.G.

public class ClassCalc
    {
        public ClassCalc(double varEm, 
                          List<List<double>> col1, 
                          List<List<double>> col2)
        {
          //set fields etc.
        }

        public void CalcCols(){
           //here, I will 'zip' col1/col2 to create List<double> for each
        }

        public void CalcStep2(){
           //this is dependent on the results from CalcCols()
        }

        public void CalcNonDependent(){
           //this can be called at any stage
        }
}

The constructor forces the client to supply the relevant data, so there's an obvious ways to do this, by calling the methods in the constructor, this way, I know that everything will be populated. But, this doesn't seem like a clean solution, especially when I want to unit test parts of the code.

If I want to unit test CalcNonDependent(), I need to fully initialize the object, when I might not even require the result of the other two calculations.

So, my question, is there a pattern that can be used for this particular scenario; I have looked at Chain of Responsibility & Command Pattern, but wondered if anyone has any suggestions

like image 235
Christian Phillips Avatar asked May 11 '26 03:05

Christian Phillips


1 Answers

Have you looked at Template? Not sure if it applies to your situation 100% but you would have a base class which defines 3 abstract methods and then calls them in the correct order.

class SomeBaseClass
{
    public abstract void CalcCols();

        public abstract void CalcStep2();

        public abstract void CalcNonDependent();

    public void DoAllCalculations() 
    {
        CalcCols();
        CalcStep2();
        CalcNonDependent();
    }
}

Then you inherit from this class and provide concrete implementations of your calculation methods.

like image 169
Ben Avatar answered May 12 '26 18:05

Ben