Be a Developer, not a Blender

Increase your Cohesion

A class with cohesion is a class that has only one purpose, not two or three. Take a look at the code below:

public class CustomerService {
    public void activateCustomer(Customer customer) {
        // activate
        // persist in database
        // create audit data
        // send email
    }
 
    private void activate(Customer customer) {
        // apply the rules
    }
 
    private void persistInDatabase(Customer customer) {
        // populate and persist the data
    }
 
    private void createAuditLog(Customer customer) {
        // create the log and persist in the database
    }
 
    private void sendEmail(Customer customer) {
        // email engine
    }
}

Because of the activateCustomer method the class now has 4 distincts responsibilities, too many for a single class. When a class has a lot of responsibilities we can classify it as incohesive.

There are several patterns and good practices that could be applied to solve the problem above. Below is a suggestion:

public class CustomerService {
    // attributes
 
    public void processNewCustomer(Customer customer) {
        customerActivationService.activate(customer);
        customerRepository.save(customer)
        auditJmsFacade.create(customer);
        emailSender.send(customer);
    }
}

About the code above:

  • The method name was edited, the new name indicates that a processing will occur and could involve some steps
  • Every action was delegated to a different class
  • Each class runs only one action of the processing, we will not have a class that will have several different methods

Other updates could be applied to that class and added to the code above. My point here is to only show that when you increase the Cohesion of your class, you make it easier to evolve and maintain your code.

Conclusion

The good practice is: “keep your classes small and cohesive”. Do not add too many responsibilities to a class, e.g. do not create a class that will send an email and format a file in the same method or in the same class.

2 thoughts on “Be a Developer, not a Blender

Leave a Comment