I think the violated priciple could be Open Closed but how can i solve this ?
public void driveCar(Car car) {
if(car instanceof PersonalCar){
((PersonalCar) car).drive();
}else if (car instanceof SportCar){
((SportCar) car).driveFast();
}
}
CodePudding user response:
Yes, Open Closed principle because if you add a new type of car, you also have to modify the method driveCar. To solve it, you need to eliminate the conditionals (if statements) and replace them with inheritance and overriding the drive() method in each car subclass. I will leave the implementation for you to complete.
CodePudding user response:
- it’s a good question, I run into the situation every day
- For better clarity, I will point out one thing, PO is trying to call drive method for normal car, and driveFast method for the sport car
- I think if sport car implement both drive and drivefast method, this class may break Single response principle, if you break this one, then you know the code will be messy, check if it is what you want and maybe you can simplify the class and leave only one method “drive”, then everything is good
- If you can not simplify the sports-car class, and still want to reduce code right here, I think you have to deal with at least 2 situations in the drive method in sports car class, you should pass parameters/state to the class and let it know whether it is dealing with normal drive or driveFast.
- Or just don’t follow the solid right now and leave the refactoring later on and maybe then you will have a better understanding and probably come up with a better solution