Object Cohesion: Why It Matters


You most probably know about Elegant Objects (EO),
an alternative object-oriented paradigm, which claims that objects must
be immutable, have no
static methods ,
never use
NULL in their code,
use no annotations ,
and so on. We, the EO adepts, claim many things, but not so many people
believe us. Those non-believers say
that we are trolls, at best. Their main argument is: everybody works differently,
why should we listen to you? I have no answer for them… well I had no answer, until I
created jPeek and started researching object cohesion .

Кин-дза-дза! by Георгий Данелия Let me explain how cohesion can help us, EO adepts, to prove some of our
assumptions.

Cohesion ,
as a characteristic of a software module, was invented by
Larry Constantine
when I didn’t even exist yet, in 1974.
Here is what it means; take a look at this simple Java class:

class Books {
private List < String > titles ;
private List < Integer > prices ;
void addTitle ( String title ) {
this . titles . add ( title );
}
void addPrice ( Integer price ) {
this . prices . add ( price );
}
} There are two attributes and two methods. The method addTitle() works with
the attribute titles , while the method addPrice() works only with the
attribute prices . The cohesion is low in this class, because the attributes
titles and prices are not related to each other in any way. We can easily
break this class into two pieces without losing anything:

class Books1 {
private List < String > titles ;
void addTitle ( String title ) {
this . titles . add ( title );
}
}
class Books2 {
private List < Integer > prices ;
void addPrice ( Integer price ) {
this . prices . add ( price );
}
} Now, we have two much more cohesive classes: their attributes and methods
are related to each other. We can’t break Books1 anymore, since each
attribute is needed by each method.

Here is yet another example of a highly cohesive class:

class Books {
private List < String > titles ;
void add ( String title ) {
this . titles . add ( title );
}
void delete ( int id ) {
this . titles . remove ( id );
}
} Can we break it into smaller pieces? No, we can’t. We can’t take any part
of the class out. The attribute titles and both of the methods must stay
together. This means that the class is highly...

Top