Cohesion in Java is the Object-Oriented principle that a class should be designed with a single, well-defined purpose. The more focused a class is, the more is the cohesiveness of that class. Having high cohesion ensures that classes are easier to maintain, requiring fewer changes than low-cohesion classes. It also ensure a higher degree of reusability than classes with low cohesion.
example of class without cohesion:
public class Worker (){
String name;
double [] pay;
public void setName (String name){
this.name = name;
}
public String getName(){
return name;
}
public void setPay(double[] pay){
this.pay = pay;
}
public double calculateMeans(){
return means;
}
}
//
The same class with improved cohesion:
public class Worker (){
String name;
double [] pay;
public void setName (String name){
this.name = name;
}
public String getName(){
return name;
}
public class Pay {
Worker worker;
double [] pay;
public Pay (Worker, worker){
this.worker = worker;
}
}
public void setPay(double[] pay){
this.pay = pay;
}
public double calculateMeans(){
return means;
}
}
Notice the addition of the class Pay, improving the focus of the code and making it more cohesive.
No comments:
Post a Comment