Composition to Change Runtime Behavior
00:14 This is helpful in certain circumstances, but it creates rigid designs that are hard to change moving forward. Composition, on the other hand, creates a loosely-coupled relationship that enables flexible designs and can be used to change behavior at run-time.
00:34 Let’s say that requirements change and now we need to support a longterm disability policy, or LTD policy, for short. This policy states that an employee on LTD should be paid 60% of their weekly salary, assuming 40 hours per week.
The new pay will be 60% of this. To follow the interface in the
PayrollPolicy, we also need a
.track_work() method, which will accept the number of hours to work and then track employees for that time.
We’ll follow similar steps for the
.calculate_payroll() method. We’ll check the
._base_policy, and if that checks out okay, we’ll get the employee’s normal
base_salary and return 60% of that. Because I marked the
._base_policy instance attribute as private, I’ll create a method that we can use to set a new base policy.
Now we can utilize this new class by adding just one more method to the
Employee class. I’ll move over to
employee.py and at the bottom of that class, I will create a method called
They now have a longterm disability policy applied to them, which itself remembers their old payroll policy and uses that to calculate their new salary. And before I run this, I’m going to make sure to import this new class from the
hr module so we don’t see any more exceptions in this course.
Notice now that our sales employee,
Kevin Bacon—with the coolest name ever—previously made $1,800, but now he only makes 60% of that. As you can see, you were able to support this change just by adding a new policy and modifying a couple of interfaces.
Become a Member to join the conversation.