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.:
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:
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?13 Replies
⌛ This post has been reserved for your question.
Hey @Fragmented friends! Please useTIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here./closeor theClose Postbutton above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically marked as dormant after 300 minutes of inactivity.
In that example, you have to modify an existing class so its a modification
but the open closed principle would be about writing your code in a way that it can be extended if applicable
also your code has a bug
and you might want to use an enum instead of
Strings
(then you can also use an exhaustive switch)its just a pseudocode for the sake of example
i think the factory pattern for this would be better
that's for constructing object and not applicable to this question
lol wrong pattern
i meant the strategy one
making a component for each color
nah we don't need that
What's the next suggestion? A visitor for all the colors? 😂
(Don't do that - use
switch instead if you want that - which is also better than a strategy in most cases similar to the one described (or just create a method in the enum or whatever object you are using instead of colors if applicable lol))I told OP yesterday to read about the expression problem
Which is why open-closed is a "sometimes"
its called overengineering
new trend in programming
💤 Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived.
If your question was not answered yet, feel free to re-open this post or create a new one.
In case your post is not getting any attention, you can try to use /help ping.
Warning: abusing this will result in moderative actions taken against you.