Java Reference
In-Depth Information
however, look at how three of the principles can be applied in the context of lambda expres-
sions. In the Java 8 context, some of the principles can be extended beyond their original
limitations.
The Single Responsibility Principle
Every class or method in your program should have only a single reason to change.
An inevitable fact of software development is that requirements change over time. Whether
because a new feature needs to be added, your understanding of your problem domain or
customer has changed, or you need things to be faster, over time software must evolve.
When the requirements of your software change, the responsibilities of the classes and meth-
ods that implement these requirements also change. If you have a class that has more than
one responsibility, when a responsibility changes the resulting code changes can affect the
other responsibilities that the class possesses. This possibly introduces bugs and also im-
pedes the ability of the code base to evolve.
Let's consider a simple example program that generates a BalanceSheet . The program
needs to tabulate the BalanceSheet from a list of assets and render the BalanceSheet to a
PDF report. If the implementer chose to put both the responsibilities of tabulation and ren-
dering into one class, then that class would have two reasons for change. You might wish to
change the rendering in order to generate an alternative output, such as HTML. You might
also wish to change the level of detail in the BalanceSheet itself. This is a good motivation
to decompose this problem at the high level into two classes: one to tabulate the Balan-
ceSheet and one to render it.
The single responsibility principle is stronger than that, though. A class should not just have
a single responsibility: it should also encapsulate it. In other words, if I want to change the
output format, then I should have to look at only the rendering class and not at the tabulation
class.
This is part of the idea of a design exhibiting strong cohesion . A class is cohesive if its meth-
ods and fields should be treated together because they are closely related. If you tried to di-
vide up a cohesive class, you would result in accidentally coupling the classes that you have
just created.
Now that you're familiar with the single responsibility principle, the question arises, what
does this have to do with lambda expressions? Well Lambda expressions make it a lot easier
Search WWH ::




Custom Search