Search code examples
coupling

Loose Coupling vs. Information Hiding and Ease of Change


I'm just reading Code Complete by Steve McConell and I'm thinking of an Example he gives in a section about loose coupling. It's about the interface of a method that calculates the number of holidays for an employee, which is calculated from the entry date of the employee and her sales. The author suggests a to have entry date and sales as the parameters of the method instead of an instance of the employee:

int holidays(Date entryDate, Number sales)

instead of

int holidays(Employee emp)

The argument is that this decouples the client of the method because it does not need to know anything about the Employee class.

Two things came to my mind:

  1. Providing all the parameters that are needed for the calculation breaks encapsulation. It shows the internals of the method on how it computes the result.

  2. It's harder to change, e.g. when someone decides that also the age of the employee should be included in the calculation. One would have to change the signature.

What's your opinion?


Solution

  • The problems I see with your argument number 2 are

    1. you are assuming every needed value comes from an Employee instance. This is by no means always true. For example, say you have to consider the financial state of the company to calculate how much 'bonus holiday' give to any employee. Would you add financial state information to the employee class to avoid changing the signature?

    2. changing a signature is not necessarily "harder", especially so in these days of tools that will highlight every calling place at the click of a button.

    And the main problem with your argument number 1 is that it just doesn't break encapsulation as everyone else has said. You are showing the what, not the how, which is what encapsulation is about.