Modifying Object Behavior With Composition
00:00 One of the benefits of employing a policy-based design is that it allows us to easily change object behavior. If our design relied on inheritance, we’d need to find a way to change the type of an object to change its behavior.
00:18 With this design, all we have to do is modify one component of one object and we’re all set.
00:26
For example, imagine that our manager is in some pretty hot water with the CEO, and the CEO has decided to take away the manager’s luxurious salary and replace it with $55 per hour. That’s not too bad of a punishment for the manager, but for us, the developers hired to make this change, this could be a nightmare if our classes were tightly-coupled. To make this change with the current design, all we have to do is add two lines of code. First, I’m going to obtain the manager
, which is the first employee in our list of employees.
01:06
Then all we have to do is change his .payroll
instance attribute to an HourlyPolicy
at 55
dollars per hour.
01:16
I also have to make sure I import HourlyPolicy
into this module.
01:22 Now when I run this program, you see the manager is making $2,200 per week instead of the $3,000 they were making before. Notice that this change only required changing one module, instead of changing the code of several other modules.
01:43 If this relied strictly on inheritance, we would have had to create a new class and change the type of the manager employee. This is a much cleaner solution.
Become a Member to join the conversation.
petrovicdjordje750 on Jan. 13, 2021
Loved this HR project, however I think this is not targeted towards beginners in programming, it fells a bit heavy to learn python, OOP concepts and design patterns at the same time.