Coupling and Cohesion: Failed Concepts.
Join the DZone community and get the full member experience.Join For Free
a return to the wellspring.
to w.p. stevens, g.j. myers and l.l. constantine, programmers owe much gratitude. authors of the inexhaustibly minable 1974 paper structured design , they revealed the fundamental mechanism of ripple effect thereby pouring welcome concrete into the rather shallow foundations of software engineering. the paper also introduced to the world the blushing concepts of coupling and cohesion, concepts lauded ever afterwards. where the french revolutionaries had, "liberté, egalité, fraternité," programmers would rush into scrum meetings roaring, "loose coupling and high cohesion!" but there is a problem. taken individually, both concepts appear sound; taken together, however, they confess worrying inconsistency. a previous post having already examined coupling , this post looks at cohesion before undertaking a side-by-side evaluation.
two pairs of consecutive lines from the great work present the concept:
"coupling is reduced when the relationships among elements not in the same module are minimized. there are two ways of achieving this - minimizing the relationships among modules and maximizing relationships among elements of the same module."
"binding is the measure of the cohesiveness of a module. the objective here is to reduce coupling by striving for high binding."
(the paper avoids the term, "cohesion," preferring, "cohesiveness," but this post uses the more commonplace term.)
in fact, though the authors' later works would, the paper fails to advance an actual definition of cohesion. the above is as close as it gets. whatever form cohesion takes, binding - another nebulous term - is its measure. this vagueness might not strike as critical given the wealth of subsequent verbiage birthed by the paper, yet a darker idea lurks within the excerpts above: for what can it mean to, "maximize relationships among elements in the same module?"
as mentioned before, any review of ancient texts must tread a cautious path between monkish reverence and interpretative flaccidity. the, "module," of the paper, for example, reads as though limited to the notion of a method or function: "the term module is used to refer to a set of one or more contiguous program statements having a name by which other parts of the system can invoke it." nevertheless, license allows that, considering both the orders of magnitude by which software systems have inflated in the intervening years and the consequent structural innovations necessitated, programmers can justify expanding this, "module," term to include its modern up-gunned equivalents, with java, for instance, offering a hierarchical organization of program statements into methods, methods into classes and classes into packages (not to mention jars and bundles).
presuming, then, that cohesion applies to classes, packages, etc., two questions arise. which cohesion? and in what sense?
for the paper famously separates binding - and by implication, cohesion - into its six different strains, from the weakest, "coincidental," to the strongest, "functional." a tour of this spectrum lies beyond the scope of this post but because functional binding stands as the ultimate classification and its corresponding cohesion the goal towards which structured design claims to strive, only functional binding is considered here. the paper defines this via, "in a functionally bound module, all of the elements are related to the performance of a single function." (the single responsibility principle was alive, well and probably hitting the disco twice weekly in the early seventies.)
in which sense, then, are these elements, " ... related to the performance of a single function?" what is the nature of this relationship? source code being textual, this relationship may be either semantic or syntactic. the source code for a flight control system, for example, might gather in a single package all classes related to the raising and lowering of the landing gear. this package would then appear semantically functionally bound and hence of high cohesion. the paper suggests, however, the insufficiency of semantic relationship by discussing what it calls, "logical binding," its term for binding based on semantic relatedness. the paper defines this binding as that which, " ... implies some logical relationship between the elements of a module. examples are a module that performs all input and output operations for the program or a module that edits all data," with the paper reaching the slightly alarmist conclusion, "in short, logical binding usually results in tricky or shared code, which is difficult to modify, and in the passing of unnecessary parameters." the case is not strong, but this hints at the need for a thicker glue, that of syntax, whereby the classes of a package must syntactically depend on one another before being considered functionally bound.
consider figure 1, showing a package of classes from the recently reviewed fitnesse .
this package displays strong syntactic functional binding and thus
high cohesion. the class
depends on almost all others and so it would be hoped that this class
in some sense coordinates the others in the service of the package's
singular purpose (whatever that may be). the two straddling
divert from this goal. this seems,
at least, a
offers another good example, see figure 2.
in figure 2, two classes hold court,
, both presiding over clear dependencies
engaging the rest of the classes in the package. again, with no
mutinous sub-divisions seceding from the greater mass, this package
enjoys functional cohesion. on this issue of mutiny, programmers can
usually spot a package that lacks functional cohesion precisely
because such packages host independent constellations of classes. take
figure 3, which shows the small and apparently
nevertheless this package lacks functional cohesion because several of its classes have sloughed off from the main group, making possible a significant decomposition without breaking any dependencies, see figure 4.
figure 4: package
split into two independent parts.
figure 4 shows the same classes and dependencies as figure 3 but graphically re-arranged to show the largest connected group to the right, leaving behind those disconnected classes of which the main group makes no use. here then a package has been caught performing more than one function, the penalty for which should be a brutal refactoring just to keep other packages in line. this all smacks, however, of the graph concept of connectedness , a perfectly good concept in its own right for which no new term - such as cohesion - would seem required. this digression, though, concerns packages of low cohesion and these are not our primary quarry. we must return to packages of high cohesion.
the maximization problem.
so, packages can certainly lack cohesion but can they have too much cohesion? recall that the paper does not advise to reduce coupling by merely clarifying the relationships among elements of the same module, it speaks of, "maximizing," the relationships among elements in the same module. what might this mean? it cannot mean the arbitrary sharing of superfluous dependencies between all classes in a package; this would be silly. might it instead mean that an increase in the number of essential dependencies between classes within a package indicates better cohesion? consider figure 5, showing another fitnesse package, but this one poorly structured.
figure 5: package
figure 5 shows the package
, one in obvious
distress. the classes of this package, unlike those of the previous,
hang snared like gasping fish in a great trawl of dependencies. about
this confused tangle of relationships few clear statements can be
made. few statements, that is, save one: certainly more dependencies
stretch between classes here than between those of the previous
packages. so does this mean that the
package has a
most programmers, surely, would think not. or if they did so, they might say that, yes, perhaps this package has more cohesion but then cohesion itself has its limits, beyond which it delivers no structural benefit and may even drag a system into structural debt. this latter opinion might find itself rejected, however, on the basis of the sheer unpopularity of the battle cry, "loose coupling and sufficient cohesion."
the distinctness problem.
if figure 5 does not have a higher cohesion than previous examples, programmers must ask why. why is maximising the relationships among elements in the same module - in this case, classes in the same package - undesirable? the answer lies in ripple effects, " ... where changes in one part cause errors in another, necessitating additional changes elsewhere, giving rise to new errors, etc." if the elements within a module are too tightly inter-connected then predicting the cost of change becomes difficult because a change detonated in any element may explode, consuming many others.
this, however, presents another problem, for this desire to
minimize potential ripple effects has surfaced before, it being the
sole motivation for coupling. yes, coupling is defined as the strength
of association between - rather than within - modules but this does
not restrict ripple effects to the realm of the inter-modular. ripple
effects respect no boundary, ploughing into and through packages as
much as between them. given a transitive dependency of three
may potentially impact both
irrespective of whether the three classes reside in
one package or three. imagining transitive dependencies dissected into
those parts that fall within a package and those that fall without may
offer solace to over-worked programmers groping to understand a small
slice of a system but does not curtail the transitive dependencies
and it is in terms of ripple effects that figure 5 differs from its forebears: tracing potential ripple effects in figure 5 has become far more difficult - and hence far more potentially costly - than in previous figures. so here we have both coupling and cohesion serving the same master and towards the same ends: ripple-effect minimization. why, then, have two distinct concepts instead of one?
the perspective problem.
a further complication arises, that of perspective. coupling and
cohesion have absolute meaning only in systems that admit just two
individual levels, that of containing module and that of contained
element. if programs only had, "contiguous program statements,"
(elements) within methods (modules) then coupling would exclusively
apply to method-to-method dependencies and cohesion exclusively to
those executive dependencies between statements within methods. but
that world, if ever it existed, has gone forever. java's hierarchical
containment structures, as mentioned, tower far above the mere
method. looking again at figure 5, we see that it portrays the
cohesion of the
package because, considering a
package to be a module of elements (in this case, classes), and
according to the concept of cohesion, the figure presents the
relationships among elements within the
module. yet if a programmer considers a class to be a module of
elements (in this case, methods) then figure 5 simultaneously shows a
coupling diagram where, according to the concept of coupling, we can
see the associations established by connections from one module to
whether figure 5 portrays coupling or cohesion depends not on inherent properties of the packages or classes displayed but on viewer perspective. so it makes no sense to apply different rules for evaluating different levels within a containment hierarchy when a module at one level is also an element on the lower level but seen from a different perspective. this, alas, appears to be the goal to which the mantra, "loose coupling and high cohesion," leads, offering no guidance on the levels to which each part applies and instead inferring application to all. yet how do we achieve, " ... minimizing the relationships among modules and maximizing relationships among elements of the same module," when those relationship-maximized elements are to be the relationship-minimized modules of the level below?
ripple effect the leveller.
such problems undermine the validity of coupling and cohesion but do not in any way call into disrepute hierarchical containment per se, such containment enabling the indispensable property of encapsulation . encapsulation does not and cannot limit actual transitive dependencies, instead by information-hiding elements within boundaries it reduces the targets to which transitive dependencies can spread, thereby limiting future potential dependencies ; encapsulation is dependency management done at the appropriate time: well in advance. nor does the underlying threat of ripple effects diminish whatsoever: unpredictability of change cost remains the twenty-first century's most ferocious digital gorgon. if anything, abandoning the distracting concepts of coupling and cohesion only emphasizes the dread importance of ripple effects.
for ripple effects, there is only structure. given that a structure is a set of elements and their inter-relationships, then java source code boasts many levels of structure: method-level, class-level, package-level, etc., but over such taxonomic detail ripple effects stand aloof, leaping from method-to-method just as virulently as from package-to-package. this holds out the promise of unification, of a single level-agnostic concept that applies universally, whose jurisdiction encompasses entire programs rather than isolated districts. if ripple effects be the enemy and transitive dependencies the vector along which they propagate, then reducing transitive dependency length becomes one sensible strategy (and there are many) in this ceaseless war on costs. programmers cannot, of course, whip out a measuring tape for each of the countless transitive dependencies charging through a system, but defining depth as the average length of all a structure's transitive dependencies those programmers can avail of the principle of depth , which states merely that structures be kept shallow.
software systems are big.
fortunately, examining a small part of a system in isolation can be immensely useful. combing over the classes in a single package, for instance, ignoring all dependencies entering and leaving that package can provide invaluable insight. but it is a convenient myth and a myth which serves analytical ends only. as soon as this pretense becomes a design factor - as soon as programmers design classes within a package as though they had no connection with the rest of the system when, in fact, they do - then the myth darkens and design crumbles. one cohesive package does not make a cohesive system. no amount of cohesive packages makes a cohesive system. no amount of loosely coupled packages makes a loosely coupled system. with the pieces not adding up to the whole, programmers scratch their heads as yet another, "loosely coupled and highly cohesive," system dies not in the field but in the finance department, exit wounds on its chest.
the pity of coupling and cohesion is that they are localized analytical measures misused as globalized design ideals. forged as weapons with which to combat ripple effects, both suffer from a fatal impurity: they build on the flawed premise that ripple effects bang against magical impervious borders capable of perfectly compartmentalizing our source code. ripple effects, neutrinos of the software world, know no such borders. what can stop them? a thousand light-years of lead will. short transitive dependencies might. myths won't.
photo credit attribution.
Opinions expressed by DZone contributors are their own.