jeudi 29 août 2019

Problem with design of existing code (initialization of actions to perform)

I have architectural problem with existing code and am looking for a clean-code solution. I cannot show real code, but will show analogy.

Let's suppose that we have a car repair workshop. There are orders which can contain one or any number of actions (from known set) to perform. When worker is free, he execute operations according to current order.

But there's one main limitation: for some reasons Worker must have method PerformRepair( ) (this interface cannot be modified) and all operations should be executed on its call.

Now I have class RepairConfiguration, representing order with boolean values for all possible actions (bool ShouldChangeTyres, bool ShouldChangeEngineOil, bool ShouldRepairBrakes etc.). Worker is initialized with this RepairConfiguration. And when he PerformRepair( ), he checks each boolean and perform action if it's needed.

It look like this:

//cannot be modified
public interface IWorker
{
    void PerformRepair( );
}

//worker implementation and all below CAN be modified
public class Worker : IWorker
{
    RepairConfiguration _repairConfiguration;
    AssignRepairConfiguration( RepairConfiguration config ) { _repairConfiguration = config; }
    PerformRepair( )
    {
        if( _repairConfiguration.ShouldChangeEngineOil )
            ChangeOil( );
        if( _repairConfiguration.ShouldRepairBrakes )
            RepairBrakes( );
        if( _repairConfiguration.ShouldChangeRim || _repairConfiguration.ShouldChangeTyres )
            TakeOffWheels( ); //some preparatory - common for a few actions
        if( _repairConfiguration.ShouldChangeTyres )
            ChangeTyres( );
        if( _repairConfiguration.ShouldChangeRim )
            ChangeRim( );
    //...... other conditions checking and actions
    }
      //implementation of all actions
}

public class RepairConfiguration
{
    bool ShouldChangeTyres;
    bool ShouldChangeEngineOil;
    bool ShouldRepairBrakes;
    bool ShouldChangeRim;
    //...... other bool conditions
}

As you can see, Worker implementation don't look good. There are a lot of IFs. And even if one action should be executed all conditions are checked. It also doesn't follow open/closed principle - when there is new possible action I need modify RepairConfiguration and Worker implementations. I wanted to ask you: how would you implement that? Are there any design patterns which could be helpful?

Aucun commentaire:

Enregistrer un commentaire