by BehindJava
What is Cohesion? Is High Cohesion or Low Cohesion better in Microservices
In this tutorial, we are going to learn about the Cohesion and its types in the Microservices which is an important question in the interview room.
Cohesion
Cohesion is a measure of the degree to which the elements of a module, software or code are related.
or
Cohesion is a degree to which all elements of a module, software or code are directed towards performing a single task.
High Cohesion is GOOD!
Example of Low Cohesion
- Helper classes that are supported in many languages, such as Java and C sharp.
- Lets look at this hypothetical example, here we have a Helper class that has few methods as shown below. DateToString converts a date to String or text, GetSmtpConfig is to get the SMTP config and SmtpConfig is a class type and LogError, logs an error message to the file.
public static class Helper
{
public static string DateToString(DateTime dateTime){........}
public static SmtpConfig GetSmtpConfig();
public static void LogError(String error);
}
- You can notice that this Helper class has three methods and those methods are not related. So there is a low amount of Cohesion in that Helper class.
- It would be better to have three different concrete classes with different methods i.e., one would be of conversion of date to String or text another would be to get the SMTP configurations and one for logging the errors.
- Then there wouldn’t be any static classes which is a best practice to follow while coding an application. But instead we could use the dependency injection to inject the concrete classes using @Autowired annotation.
Note: An ideal application must be Highly Cohesive and loosely Coupled.