In short:
In object-oriented programming, the open–closed principle states "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification"; that is, such an entity can allow its behaviour to be extended without modifying its source code. Every module, class, or function in a computer program should have responsibility over a single part of that program's functionality.
Who doesn't like pizza?
Take a look at the classes in this folder. Note the PizzaRestaurant
class, that
is responsible for making (baking!) Pizza
instances. Pizzas are made by creating a base and adding
toppings to it.
Now take a look at the Pizza
class, which acts as the model of what a pizza is. As you
can see, a pizza can contain different toppings. You can also get the total grams of salt that is in a
pizza, by calling Pizza->getGramsOfSalt()
.
How can we apply the open-closed principle to improve the
Pizza
class and the toppings?
How does this affect the
PizzaRestaurant
class?