Java Community | Help. Code. Learn.JC|HCL
Java Community | Help. Code. Learn.โ€ข12mo agoโ€ข
23 replies
bambizas19

how does open-closed principle really work?

hey guys. i have a question an id like to hear other opinions. lets say i have this.:
public class MyService{
  //class fields, getters, setters
  public myServiceMethod(Car car){
    if(car.getColor()=="Red"){
      Print("Red car");
    }
    if(car.getColor()=="Green"){
        Print("Green car");
      }
    //do other business logic
  }
}

it works fine. but then there comes a point when i need to check if the car is Yellow and Blue. then it means i have to add more if statements:
public class MyService{
  //class fields, getters, setters
  public myServiceMethod(Car car){
    if(car.getColor()=="Red"){
      Print("Red car");
    }
    if(car.getColor()=="Green"){
        Print("Green car");
    }
    if(car.getColor()=="Yellow"){
        Print("Yellow car");
    }
    if(car.getColor()=="Blue"){
        Print("Blue car");
    }
    //do other business logic
  }
}

now the questions arise:
1. is adding more if statements considered to be extension or modification? In my understanding its both. You modify code all the time. You changed variable name? Its modification. In Cambridge dictionary modification is described as a change to something. Refactoring is modification too. You cant write excellent code from the first try.
2. does the first and second pieces of code follow open-closed principle? why?
Was this page helpful?