Will it break SOLID principle?

132 views Asked by At

I'm trying to write a generic method which get called and based on object type it should set indicators.

  1. Will it break any solid principles?
  2. Is there a better way of doing it?

I was working on one of the features where I have 3 lines of business like Car, Van and Bike.

I have IVehicle interface which is handling all the common implementation between the 3 lines of business.

Now, I have to set two common indicator Car and Van but for Bike, I want to set some different indicator. I want to create an object of this class once but it handle based on type of line business.

If write this method like this will it break any SOLID principles? If it is incorrect, can you please suggest an alternative?

Note: INDICATOR_B should be true in all LOB

function populateIndicator() {
  if (_motorObject typeis Car or _motorObject typeis entity.Van) {
    _motorObject.INDICATOR_A = true
  }

  if (_motorObject typeis Bike) {
    _motorObject.INDICATOR_C = true
  }

  _motorObject.INDICATOR_B = true
}
3

There are 3 answers

0
R.Abbasi On

Short version: use polymorphism to implement populateIndicator method.

Checking types in the base class breaks Liskove substitution principle. If you have a duplicate code for assigning like _motorObject.INDICATOR_B = true you can use template method pattern.

abstract class VehicleBase{

   public void populateIndicator(){

      conceretePopulateIndicator();
      // common code for all derived classes
      _motorObject.INDICATOR_B = true;
   }

   protected abstract void conceretePopulateIndicator();

}

public class Bike: VehicleBase{

    protected override void conceretePopulateIndicator(){
        _motorObject.INDICATOR_C = true
    } 
}

this design won't break any rules.

0
Ashish On

You can use rule factory here. You can define three rules. Each rule will accept type which will have one of two values Four Wheeler/Two Wheeler. You can set indicator accordingly in rule. It will not break SOLID principle.

0
Oleg Ushakov On

Yes it will break open-closed principle.

You can create interface with function populateIndicator() and default implementation _motorObject.INDICATOR_B = true And other classes Car, Van, Bike in you case should implement interface and override default method in their own way in case it applicable