The principle of high cohesion refers to the idea of designing components or modules in a system such that each component or module performs a single, well-defined task and is tightly focused on that task. High cohesion means that all the elements inside a component or module are highly related to each other and work together to achieve a common goal.
In software design, high cohesion is achieved by grouping related elements together, such as related data and functions, and by minimizing the number of interactions between components or modules. The result is that each component or module is self-contained and has a single, well-defined responsibility.
High cohesion leads to several benefits, including increased maintainability and reusability. When a component or module has a high degree of cohesion, it is easier to understand, modify, and reuse. Additionally, a system with high cohesion is more flexible and easier to test, since changes can be made in isolation without affecting other parts of the system.
Example
Here is an example of high cohesion in Java:
public class Customer {
private String name;
private String email;
public Customer(String name, String email) {
this.name = name;
this.email = email;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
}
public class CustomerService {
private List<Customer> customers;
public CustomerService() {
this.customers = new ArrayList<>();
}
public void addCustomer(Customer customer) {
customers.add(customer);
}
public List<Customer> getCustomers() {
return customers;
}
}
In this example, the Customer class has a high degree of cohesion, since all its elements, the name and email fields, are highly related and work together to represent a customer. The CustomerService class also has a high degree of cohesion, since all its elements, the customers list and the add and get methods, are related and work together to manage customers.
Conclusion
High cohesion makes it easier to understand, modify, and reuse components or modules, since all the elements inside a component or module are highly related and focused on a single, well-defined task. Additionally, high cohesion makes it easier to test and debug code, since each component or module can be tested in isolation.