Architecture is full
of examples of items designed to do more than one thing. Your smart phone is a flash light. From my last examples, a chair is also a
clothes hanger. A seat cushion is a
flotation device.
Robert Martin said
in his book Agile Software Development, Principles, Patterns, and Practice (http://en.wikipedia.org/wiki/Robert_Cecil_Martin), that every class should have a single
responsibility over a part of the function.
The function-part should be encapsulated and the class should do that
and only that.
I understand the
need for this as it makes the class easy to understand. It also could reduce the introduction of
bugs. Have you ever worked with
"spaghetti code"? You make a
change and it causes a bug in another area you couldn’t have imagined in your
wildest dreams. If a class has two
different things it does, and you change one thing, it could affect the other
piece and thus break something. Martin
gives an example a class that compiles AND prints a report. If the content of the report changes, the
class must change. If the format of the
print must change, then the class changes.
Martin argues that there is no reason for these two things to be coupled
because if the format of the print changes, the content does not change and
thus should not need to be recompiled and tested. Martin says a class should
have only one reason to change (not two, like in this example).
In an imperfect
world, needs of software change over time.
An example: My manager is crazy over this particular module we have to
is used to access and configure accounting data. Over time it has evolved to access security
data as well. This drives him crazy
because it violates the single responsibility principle (although he doesn't
call it that and doesn't know that Robert Martin invented the term). I however, think this is OK, and have argued
this fact with him. Given the schedule
pressures we were under to combine these two pieces, which are closely related
in our system, is not horrific. Not
perfect but not catastrophic either.