How to keep objects focused, understandable, and
manageable, and as a side effect, support Low Coupling?
In terms of object design, cohesion
(or more specifically, functional cohesion) is a measure of how strongly
related and focused the responsibilities of an element are. An element with
highly related responsibilities that does not do a tremendous amount of work
has high cohesion. These elements include classes, subsystems, and so on.
Solution
Assign a responsibility so that cohesion remains high.
Use this to evaluate alternatives.
A class with low cohesion does many unrelated things or does
too much work. Such classes are undesirable; they suffer from the following
problems:
·
hard to comprehend
·
hard to reuse
·
hard to maintain
·
delicate; constantly affected by
change
Low cohesion classes often represent a very "large
grain" of abstraction or have taken on responsibilities that should have
been delegated to other objects.
Here are some scenarios that illustrate varying degrees of
functional cohesion:
1.
Very low cohesion A class is solely responsible for
many things in very different functional areas.
o
Assume the existence of a class
called RDB-RPC-Interface which is completely
responsible for interacting with relational databases and for handling remote
procedure calls. These are two vastly different functional areas, and each
requires lots of supporting code. The responsibilities should be split into a
family of classes related to RDB access and a family related to RPC support.
2.
Low cohesion A class has sole responsibility for
a complex task in one functional area.
o
Assume the existence of a class
called RDBInterface
which is completely responsible for interacting with relational databases. The
methods of the class are all related, but there are lots of them, and a
tremendous amount of supporting code; there may be hundreds or thousands of
methods. The class should split into a family of lightweight classes sharing
the work to provide RDB access.
3.
High cohesion A class has moderate
responsibilities in one functional area and collaborates with other classes to
fulfill tasks.
o
Assume the existence of a class
called RDBInterface
that is only partially responsible for interacting with relational databases.
It interacts with a dozen other classes related to RDB access in order to
retrieve and save objects.
4.
Moderate cohesion A class has lightweight and sole
responsibilities in a few different areas that are logically related to the
class concept but not to each other.
o
Assume the existence of a class
called Company that is completely responsible
for (a) knowing its employees and (b) knowing its financial information. These
two areas are not strongly related to each other, although both are logically
related to the concept of a company. In addition, the total number of public
methods is small, as is the amount of supporting code.