Simberon Design Minute
 

Object Mutation

I often see developers using inheritance to paint themselves into a corner. Suppose you have a class for an Employee with subclasses for SoftwareDeveloper, SalesPerson, Manager and CEO. At first, this organization may look fine, but then you realise that you're running into problems. First, your company may hire an accountant who doesn't fit into the system. To support Accountants, you need to wrote some new code and redeploy the system. The second problem is that employees can change roles over time. They may start as SoftwareDevelopers then later move to Managers. A Manager may become the new CEO. When the employee changes roles, you'll need to migrate that employee to a new class. This is often difficult to do. You don't want to be mutating objects. Instead, try first to see if you can support all the functionality in one general-purpose Employee class. Don't worry, it's still an object oriented solution even if you don't use inheritance. If there really are behavior differences, then abstract those differences into a separate class hierarchy like a Role and store the role as an instance variable in the Employee. Try to avoid mutating objects.

Download