Java Reference
In-Depth Information
6.7
Responsibility-driven design
We have seen in the previous section that making use of proper encapsulation reduces coupling
and can significantly reduce the amount of work needed to make changes to an application.
Encapsulation, however, is not the only factor that influences the degree of coupling. Another
aspect is known by the term responsibility-driven design.
Concept:
Responsibility-
driven design
is the process of
designing classes
by assigning well-
defined responsibili-
ties to each class.
This process can
be used to deter-
mine which class
should implement
which part of an
application function.
Responsibility-driven design expresses the idea that each class should be responsible for han-
dling its own data. Often, when we need to add some new functionality to an application, we
need to ask ourselves in which class we should add a method to implement this new function.
Which class should be responsible for the task? The answer is that the class that is responsible
for storing some data should also be responsible for manipulating it.
How well responsibility-driven design is used influences the degree of coupling and, therefore,
again, the ease with which an application can be modified or extended. As usual, we will dis-
cuss this in more detail with our example.
6.7.1
Responsibilities and coupling
The changes to the Room class that we discussed in Section 6.6.1 make it quite easy now to add
the new directions for up and down movement in the Game class. We investigate this with an
example. Assume that we want to add a new room (the cellar) under the office. All we have to
do to achieve this is to make some small changes to the Game 's createRooms method to create
the room and to make two calls to set the exits:
private void createRooms()
{
Room outside, theater, pub, lab, office, cellar;
...
cellar = new Room("in the cellar");
...
office.setExit("down", cellar);
cellar.setExit("up", office);
}
Because of the new interface of the Room class, this will work without problems. The change is
now very easy and confirms that the design is getting better.
Further evidence of this can be seen if we compare the original version of the printLoca-
tionInfo method shown in Code 6.2 with the getExitString method shown in Code 6.6
that represents a solution to Exercise 6.7.
Code 6.6
The getExitString
method of Room
/**
* Return a description of the room's exits,
* for example, "Exits: north west".
* @return A description of the available exits.
*/
 
 
Search WWH ::




Custom Search