Vertical vs. Horizontal Decomposition of Responsibility
Objects with too many responsibilities are often prime candidates for refactoring. We take a look at the Decomposition of Responsibility pattern for performing these refactorings. Read on to find out more about the pattern and how to use (and not use) it.
Join the DZone community and get the full member experience.
Join For Freeobjects responsible for too many things are a problem. because their complexity is high, they are difficult to maintain and extend. decomposition of responsibility is what we do in order to break these overly complex objects into smaller ones. i see two types of this refactoring operation: vertical and horizontal. and i believe the former is better than the latter.
let's say this is our code (in ruby):
obviously, objects of this class are doing too much. they save log lines to the file and also forward them — an obvious violation of a famous
single responsibility principle
. an object of this class would be responsible for too many things. we have to extract some functionality out of it and put that into another object(s). we have to
decompose
its responsibility. no matter where we put it, this is how the
log
class will look after the extraction:
now it only saves lines to the file, which is perfect. the class is cohesive and small. let's make an instance of it:
next, where do we put the lines with formatting functionality that were just extracted? there are two approaches to decompose responsibility: horizontal and vertical. this one is horizontal :
in order to use
log
and
line
together, we have to do this:
see why it's horizontal? because this script sees them both. they both are on the same level of visibility. we will always have to communicate with both of them when we want to log a line. both objects of
log
and
line
are in front of us. we have to deal with two classes in order to log a line:
to the contrary, this decomposition of responsibility is vertical :
class
timedlog
is a decorator, and this is how we use them together:
now, we just put a line in the log:
the responsibility is decomposed vertically. we still have one entry point into the
log
object, but the object "consists" of two objects, one wrapped into another:
in general, i think horizontal decomposition of responsibility is a bad idea, while vertical is a much better one. that's because a vertically decomposed object decreases complexity, while a horizontally decomposed one actually makes things more complex because its clients have to deal with more dependencies and more points of contact.
Published at DZone with permission of Yegor Bugayenko. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments