Java — Cohesion in Java | Code Factory

  • In object oriented design, cohesion refers all about how a single class is designed. Cohesion is the Object Oriented principle most closely associated with making sure that a class is designed with a single, well-focused purpose.
  • The more focused a class is, the cohesiveness of that class is more. The advantages of high cohesion is that such classes are much easier to maintain (and less frequently changed) than classes with low cohesion. Another benefit of high cohesion is that classes with a well-focused purpose tend to be more reusable than other classes.
  • Example : Suppose we have a class that multiply two numbers, but the same class creates a pop up window displaying the result. This is the example of low cohesive class because the window and the multiplication operation don’t have much in common.
  • To make it high cohesive, we would have to create a class Display and a class Multiply. The Display will call Multiply’s method to get the result and display it. This way to develop a high cohesive solution.
class Multiply { 
int a = 5;
int b = 5;
public int mul(int a, int b)
{
this.a = a;
this.b = b;
return a * b;
}
}

class Display {
public static void main(String[] args)
{
Multiply m = new Multiply();
System.out.println(m.mul(2, 2));
}
}
4
  • High cohesion is when you have a class that does a well defined job. Low cohesion is when a class does a lot of jobs that don’t have much in common.
  • High cohesion gives us better maintaining facility and Low cohesion results in monolithic classes that are difficult to maintain, understand and reduces re-usability.

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to Launch the Best Optimization Test — Navy SEALs Style

Architecture Design Competition ‘Inclusivity’ Launched by UNI — Write an essay on role of gender…

Week 8: 7524QCA Visual Communication

How To Create Successful UX/IX with Design Thinking?

A simple test that will show if you talk (listen) to your customers right

Colorful & Creative: Interiors by Tobi Wright

‘The conference of society’ arranged by Norconsult

Designing for wellbeing: video games and emotions

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Code Factory

Code Factory

More from Medium

Java, JVM, JRE and JDK

Java 8 Features

Collections in Java

Java Optional