Java Reference
In-Depth Information
The following Employee3 class is even more decoupled from Address2 because it
performs the initialization of the home fi eld in one step instead of invoking multiple
methods of Address2 :
public class Employee3 {
private Address2 home;
public Employee3(String street, String city, int zip) {
home = new Address2(street, city, zip);
}
}
Unnecessary coupling decreases the reusability of the coupled objects and increases the
diffi culty of modifying your code, so loose coupling is an important design to implement
in your Java applications. The next section discusses yet another important OO design
concept: high cohesion.
High Cohesion
Cohesion refers to how closely related the specifi c tasks are of an object. High cohesion
is when an object performs a collection of closely related tasks. Low cohesion is when an
object performs multiple tasks that are not related to each other. Using low cohesion creates
code that is diffi cult to maintain and reuse; therefore, high cohesion is an important design
goal of any OO application. Classes that implement high cohesion are more reusable and
easier to test and understand.
To demonstrate cohesion, consider the following Payroll class that performs various
tasks related to paying employees of a company. Based on the names of the methods of
Payroll , see if you can determine if it follows the design principle of high or low cohesion:
public class Payroll {
public void computeEmployeePay() {
System.out.println(“Compute pay for employees”);
}
public void computeEmployeeTaxes() {
System.out.println(“Compute taxes for employees”);
}
public void addNewEmployee(Employee e) {
System.out.println(“New employee hired...”);
}
}
Search WWH ::




Custom Search