Java Reference
In-Depth Information
The Payroll class has three specifi c tasks: computing the employees' pay, computing
their taxes, and adding new employees. Computing pay and taxes are related, but adding a
new employee to the company seems unrelated to the specifi c tasks of computing paychecks.
Therefore, the Payroll class uses low cohesion and is therefore not a well-designed class.
To make Payroll highly cohesive, remove the addNewEmployee method from Payroll
and add it to a new class that is related to the tasks of hiring employees. For example, the
following HumanResources class seems like a good class to contain such a method:
public class HumanResources {
public void addNewEmployee(Employee e) {
System.out.println(“New employee hired...”);
}
public void removeEmployee(Employee e) {
System.out.println(“Employee leaving...”);
}
}
Now the hiring and removing of employees is separate from paying employees, which
results in a highly cohesive design. If we need to alter how employees are added or removed
from the company, the Payroll class will be unaffected by such a change. Similarly, if we
need to change how employees are paid, changes can be made to the Payroll class without
affecting the HumanResources class.
High Cohesion and Loose Coupling
Implementing high cohesion works in close association with loose coupling. If a class is
highly cohesive, it is easier to minimize the number of interactions the object has with
other objects, which results in looser coupling. On the other hand, if a class performs
various unrelated tasks and therefore has low cohesion, more objects will need to
communicate with the class, which results in tighter coupling.
In general, your OO applications should strive to decrease dependencies between
unrelated objects (loose coupling), while striving to create objects that perform specifi c,
related tasks (high cohesion). The result is code that is easier to maintain and reuse.
There is a direct relationship and benefi t to using tight encapsulation, loose coupling,
and high cohesion. Using tight encapsulation and high cohesion tends to result in loose
coupling, all of which result in code that is more maintainable and reusable.
Search WWH ::




Custom Search