In this new class, we would implement its new behavior: To make it follow the OCP principle, we will add a new class that will extend the Discount. Type of customers, you will see that a new logic will be added. If we want to give a new percent discount maybe, to a diff. When you decide to offer double the 20% discount to VIP customers. Let’s imagine you have a store, and you give a discount of 20% to your favorite customers using this class: ![]() Now, if we add a new animal, animal_sound doesn’t need to change.Īll we need to do is add the new animal to the animal array.Īnimal_sound now conforms to the OCP principle. The animal_sound iterates through the array of animal and just calls its make_sound method. We have each animal extend the Animal class and implement the virtual make_sound method.Įvery animal adds its own implementation on how it makes a sound in the make_sound. How do we make it (the animal_sound) conform to OCP?Īnimal now has a virtual method make_sound. In the animal_sound function each time a new animal is added, all over the application. You will see that the if statement would be repeated over and over again When your application grows and becomes complex, You see, for every new animal, a new logic is added to the animal_sound function. If we add a new animal, Snake, We have to modify the animal_sound function. The function animal_sound does not conform to the open-closed principle because it cannot be closed against new kinds of animals. Software entities(Classes, modules, functions) should be open for extension, not modification. So whenever they tend to change they change for the same reason.Īnd we should try to separate features if they will change for different reasons. When designing our classes, we should aim to put related features together, To make this conform to SRP, we create another class that will handle the sole responsibility of storing an animal to a database: You see this system smells of rigidity, it’s like a domino effect, touch one card it affects all other cards in line. The classes that make use of Animal properties will have to be touched and recompiled to compensate for the new changes. If the application changes in a way that it affects database management functions. How will this design cause issues in the future? ![]() The constructor and get_name manage the Animal properties while the save manages the Animal storage on a database. SRP states that classes should have one responsibility, here, we can draw out two responsibilities: animal database management and animal properties management. If a class has more than one responsibility, it becomes coupled.Ī change to one responsibility results to modification of the other responsibility. “…You had one job” - Loki to Skurge in Thor: Ragnarok
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |