4
The OCP principle preaches: "open to extension, but closed to alteration". To achieve this we need to abstract, because with an abstraction we can extend without needing to change the one that uses abstraction.
Consider a didactic example:
The idea is that I can extend the project by adding new letters without, however, needing to change the class Palavra
.
So far, so good: abstraction, polymorphism, OCP.
But if I need to know the amount of certain letters, the amount of letter A, B, etc.?
One of the ways to do this is by using instanceof
. But that way, I’ll be violating OCP, because with each addition of a letter, I’ll have to change the Word class to add one more if
and instanceof
to count the amount of that letter.
Finally, the questions are:
- there is a way to avoid this?
- the need to know specifically about an object misrepresents the adoption of this abstraction, that is, since I need to know about the object, I do not have to abstract this object?
- abstraction use in one sense, but inevitably concrete, specific (contrary to abstract) in another direction?
Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site
– Maniero
I think the Interface Segregation Principle (ISP) can help you a little bit.
– Vinicius.Silva