Wize Software Engineering Textbook > Software Design

Allocating Responsibilities to Classes

Assigning Responsibilities to Classes

Once you have identified the classes in an object-oriented design, a harder question remains: which class should do each piece of work? Good choices give you a design where a change stays local. Poor choices give you one where every edit ripples through half the code. The guidelines in this lesson, known as the GRASP patterns, give you a reasoned way to make that choice instead of guessing.

Knowing and doing

A responsibility is an obligation a class takes on: something it must know or something it must do. Knowing responsibilities cover data the object holds and facts it can derive or look up. Doing responsibilities cover computations, creating other objects and coordinating work among objects. A responsibility is not the same as a method. One responsibility may need several methods, sometimes spread across collaborating classes.


You usually discover responsibilities from use cases or from interaction diagrams. Each system operation must end up as a message to some object, and that object must either do the work or delegate parts of it.

The core patterns

The most-used guideline is Information Expert: give a responsibility to the class that has the information needed to fulfil it. Expert keeps behaviour next to the data it uses, so objects do things rather than handing out their fields for someone else to process.


Example: A music app needs the total running time of a playlist. Playlist holds its tracks, so it is the expert for the total. It does not know each track's length, though; Track does. So Playlist.totalDuration() asks each Track for getDuration() and adds the results. The work is split along the lines of who knows what.


A class diagram with PlayerScreen calling totalDuration on Playlist, which calls getDuration on Track.


The other patterns handle common situations and judge the results. Coupling describes how strongly a class depends on other classes; cohesion describes how closely related a single class's responsibilities are.


Pattern

Assign the responsibility to

Question it answers

Creator

A class that contains, records, closely uses or has the initialising data for the new object

Who should construct an object?

Controller

A non-UI class representing the whole system or one use case

Who receives a system event from the user interface?

Low Coupling

The option that adds the fewest dependencies

Which candidate design is easier to change?

High Cohesion

The option that keeps each class focused on related work

Is this class doing too much?

Pure Fabrication

An invented class with no counterpart in the problem domain

Where does work go when no domain class fits well?



Counting coupling and weighing trade-offs

Coupling can be counted. The fan-out of a class CC is the number of distinct other classes it depends on: classes it calls, holds a reference to, creates or receives as a parameter.


fan-out(C)=∣{ D≠C:C depends on D }∣\text{fan-out}(C) = \left|\{\, D \neq C : C \text{ depends on } D \,\}\right|


Count distinct classes, not method calls: three calls from Playlist to Track still add one to the fan-out of Playlist. Adding up every directed dependency in a design, and noting its largest single fan-out, turns a coupling argument into numbers you can compare.


In the playlist design there are two dependencies, PlayerScreen → Playlist and Playlist → Track, and no class has a fan-out above 1. Suppose instead a separate DurationCalculator pulled the tracks out of Playlist and read each Track. The design would have PlayerScreen → DurationCalculator, DurationCalculator → Playlist, DurationCalculator → Track and the existing Playlist → Track: four dependencies, with the calculator's fan-out at 2. The Expert design wins on coupling.


Patterns can pull in different directions. A Sale knows its own data, so Expert alone suggests it should save itself to a database. That would tie a domain class to database code and lower its cohesion. When Expert would damage coupling or cohesion, the yardsticks usually win, and a pure fabrication such as SaleRepository takes the job.



What to remember

  • A responsibility is something a class knows or does, and it may take several methods.
  • Information Expert gives work to the class holding the needed data, which delegates parts to the classes that know them.
  • Creator picks a class that contains, records, closely uses or initialises the new object.
  • A controller receives system events from the user interface and delegates the real work.
  • Compare designs by counting distinct dependencies; prefer fewer links and focused classes, adding a pure fabrication when no domain class fits.

Example: Late fees in a library system

A library system has these classes. A Member keeps an array of its Loan objects. Each Loan holds a reference to one Book, a due date and a return date. Each Book knows its daily late rate: €0.25 per day for a regular book and €1.00 per day for a reference book. The librarian's screen needs the total late fees a member owes.


Priya has three returned loans:


Loan

Book type

Days late

1

Regular

4

2

Reference

2

3

Regular

0


a) Decide which class should compute each loan's fee and which should compute the member's total, then find Priya's total.


Apply Information Expert at each level. The fee for one loan needs the number of days late and the book's daily rate. Loan knows its dates, so it can work out the days late, and it holds the Book that supplies the rate. Loan is the expert for one fee and asks its Book for the rate.


The member's total needs every one of the member's loans. Only Member holds that collection, so Member is the expert for the total and sums the fee each loan reports.


Loan 1 costs 4 × €0.25 = ________, loan 2 costs 2 × €1.00 = ________, and loan 3 costs nothing because it came back on time.


Adding the three fees gives €1.00 + €2.00 + €0.00 = €3.00, so Priya owes €3.00.


Java
class Member {
    private Loan[] loans;

    double totalLateFees() {
        double total = 0;
        for (Loan loan : loans) {
            total += loan.lateFee();
        }
        return total;
    }
}

class Loan {
    private Book book;

    double lateFee() {
        return daysLate() * book.getDailyRate();
    }
}


b) A teammate proposes design A instead: a new FeeCalculator class asks Member for its loans, asks each Loan for its dates and its Book, asks each Book for its rate, and does all the arithmetic itself. Call your design from part (a) design B. In both designs Member still holds its loans and each Loan still holds its book; ignore the librarian's screen, which calls exactly one class in either design. Count the distinct directed class-to-class dependencies in each design and say which design has lower coupling.


List every directed dependency in design A. FeeCalculator depends on Member, Loan and Book, so its fan-out is ________. The structure is unchanged, so Member → Loan and Loan → Book are still there. Design A therefore has 3 + 2 = 5 dependencies.


Design B has only Member → Loan and Loan → Book, which is 2 dependencies, and the largest fan-out of any class is ________.


Design B has 2 dependencies against design A's 5, so design B has lower coupling. In design A, a change to how Book reports its rate or how Loan stores its dates also reaches FeeCalculator, which has to understand the data of three classes. Design B keeps each calculation next to its data.


c) On 3 October, Priya checks out a book with a 21-day loan period. The librarian's checkout event supplies the book and the checkout date, and Member has a checkOut(book, date) method that receives them. Which class should create the new Loan, and what due date should it set?


Check the Creator criteria. Member contains and records the member's loans, and part (a)'s totalLateFees() shows it closely uses them. Its checkOut(book, date) method receives the book and checkout date, so Member also has the ________ the new Loan needs. Member therefore meets the Creator criteria. Book holds no loans. A checkout controller that built the Loan itself would take on domain work; it should receive the librarian's checkout event and call member.checkOut(book, date).


Member creates the Loan and sets its due date 21 days after checkout. October has 31 days, so there is no month rollover: 3 October + 21 days = 24 October. The due date is 24 October.

Match each responsibility-assignment pattern used in object-oriented design with the guideline it gives for deciding which class should do a piece of work.

Match each term
A.

Route each system event from the user interface to a non-UI object that coordinates the response

B.

Let a class that contains, records or initialises an object be the one that constructs it

C.

Keep each class focused on a small set of closely related tasks

D.

Prefer the option that adds the fewest dependencies between classes

E.

Invent a class with no domain counterpart when no domain class fits the job well

F.

Give the work to the class that already holds the data the work needs

High Cohesion

Pure Fabrication

Controller

Creator

Low Coupling

Information Expert

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

An online store's design has an Order class holding a list of OrderLine objects. Each OrderLine stores a quantity and a reference to one Product, and each Product stores its unit price. For example, an order might contain 3 notebooks at €2.50 and 1 pen at €1.20, for a subtotal of €8.70. Using Information Expert, which assignment of the order-subtotal responsibility is best?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A hotel booking system has five classes. The list below shows every method call, constructor call or stored reference each class makes in the current design.

  • BookingController calls Guest.findById(), Room.isFree() and Room.reserve(), creates a new Reservation, and calls RateTable.nightlyRate().
  • Reservation calls Room.getNumber(), calls RateTable.nightlyRate() twice (once for weeknights and once for weekends), and calls Guest.getName().
  • Guest calls Reservation.getTotal() to list past stays.
  • Room and RateTable call no other class.

The fan-out of a class is the number of distinct other classes it depends on. The fan-in of a class is the number of distinct other classes that depend on it. Fill in both values for each class as whole numbers.

ClassFan-outFan-in
BookingController
Reservation
Guest
Room
RateTable

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice