Hiding Delegates (OOP)

_config.yml

These ideas have been drawn from Martin Fowler’s book: Refactoring – with my own thoughts interspersed. I have elaborated where I thought Fowler fell short. Here goes:

Consider the following code:

Now any changes that you make to the GetManager() methods name (on the department class) – will not affect the client, but it will simply affect the class that’s in the middle – in this case the employee class. In other words you are basically protecting the client from having to change, at the trade-off of forcing those changes to take place in an intermediate class – in this case the employee class.

Does this reduce coupling?

It certainly makes life a whole lot easier – but the coupling in the technical sense of the term is still there. The client still knows that it needs a manager. It’s still getting a manager from the employee. The client itself doesn’t have to change, but the receiver – the employee does have to change – if we decide to make a change to the Department.GetManager() method and we decide to hide the delegation to get that manager. This is perhaps best illustrated by example.

If you have this several times in your code – littered all over the place in several different classes – if you decide to change the name of the GetManager method – then guess what - you’ll be forced to make four separate changes:

But all of this comes at a cost. If you’re creating a lot of methods in the employee class, then it is purely serving as a middle man. Think about the costs and benefits of this approach.

Summary

If you see this type of thing in your code: freddie.getManager().getTourPlanner().getWembleyCOO().getTimeslot.getAvailableTimes().BookTime() then perhaps you should reconsider your design. You’re creating a nightmare for yourself because if one thing changes down the line, you’ll perhaps be forced to make 1000s other changes. And you could potentially be spending a long time debugging.

Written on October 15, 2017