Computing EN Exam

Software Engineering 2

1,303 cards 1 Version 1, updated November 19, 2026

By downloading or studying this deck you agree to the deck directory terms, including the deck's licence.

Software engineering flashcards for the second bachelor's course: design principles, design patterns, refactoring and maintenance, and software construction in Java 17, with 17 exam-style exercises.

What's inside

  • Design Principles — modularity and information hiding, coupling and cohesion, design metrics and strategies, object-oriented concepts, SOLID and design by contract.
  • Design Patterns — all 23 classic patterns, plus dependency injection, Repository, MVC, MVP and MVVM, Null Object and Value Object.
  • Refactoring and Maintenance — code smells, refactorings, readable code, technical debt, maintenance and evolution, impact analysis and legacy code.
  • Construction — error handling, API design, generics and immutability, reuse and dependencies, concurrency, configuration, performance and tooling.
  • Practice — 17 exam-style exercises with marking schemes and model answers, including code reading and refactoring tasks.

Every card is written in our own words with our own examples, and every worked example, trace and model answer is checked by script. The Practice deck is an exam: it draws three exercises at random, and you grade your answers against each marking scheme.

1,303 cards in total.

What's inside

  • Design Principles 255 cards
  • Design Patterns 441 cards
  • Refactoring and Maintenance 289 cards
  • Construction 301 cards
  • Practice Exam 17 cards

A few cards

Design Principles

255 cards

Front

Abstraction (software design): definition

Back

A simplified view of a software element that shows what its users must know to work with it, such as what an operation does and what it needs, and hides how it does it.

core · Abstraction in models: → Software engineering 1, Modelling with UML: "Abstraction (modelling): definition".

Front

Procedural and data abstraction: the difference

Back

Procedural abstraction names a computation and hides its steps: callers of fareCents(trip) know what it returns, not how. Data abstraction names a kind of value with its operations and hides its representation: a DateRange offers overlaps(other), whatever fields it keeps.

core · Abstract data types: Liskov and Zilles 1974.

Front

RouteService.travelMinutes(from, to) in a bike-sharing app: what the abstraction lets the app ignore

Back

Where the minutes come from, a map provider's web service, a local table or a model trained on past rides, and how that source is called. The source can be switched without changing any line that calls travelMinutes.

core

Front

Remote booking service behind a method that looks like a local call: how the abstraction misleads

Back

Callers treat the call as fast and always available, but a network call can take seconds, fail halfway or succeed without the answer arriving. Such effects leak through any interface that pretends the network isn't there, so the interface should show them, with timeouts and explicit failure results.

depth · Waldo et al. 1994, "A note on distributed computing". Spolsky 2002 named leaky abstractions.

Design Patterns

441 cards

Front

Design pattern: definition

Back

A named, proven solution to a design problem that keeps coming back in a certain context: which roles classes and objects play, how they work together and what the arrangement costs. It is applied by adapting it to each design, never by copying code.

core · SWEBOK v4.0a 3:4.4. Beck and Cunningham 1987 first applied Alexander's pattern idea to programs; GoF 1994 made it widely known.

Front

Besides its name, a pattern description states the   it addresses and the context in which it arises, the solution as roles and how they work together, and the consequences: what using it buys and what it costs.

Back

Besides its name, a pattern description states the problem it addresses and the context in which it arises, the solution as roles and how they work together, and the consequences: what using it buys and what it costs.

core · GoF 1994. Tip: catalogues add sections such as intent, structure, sample code and related patterns.

Front

Besides its name, a pattern description states the problem it addresses and the context in which it arises, the   as roles and how they work together, and the consequences: what using it buys and what it costs.

Back

Besides its name, a pattern description states the problem it addresses and the context in which it arises, the solution as roles and how they work together, and the consequences: what using it buys and what it costs.

core · GoF 1994. Tip: catalogues add sections such as intent, structure, sample code and related patterns.

Front

Besides its name, a pattern description states the problem it addresses and the context in which it arises, the solution as roles and how they work together, and the  : what using it buys and what it costs.

Back

Besides its name, a pattern description states the problem it addresses and the context in which it arises, the solution as roles and how they work together, and the consequences: what using it buys and what it costs.

core · GoF 1994. Tip: catalogues add sections such as intent, structure, sample code and related patterns.

Refactoring and Maintenance

289 cards

Front

Code smell: definition

Back

A feature of the code that you can see on the surface, such as a very long method or the same three parameters in many signatures, and that often points to a design problem worth a closer look. It is a hint, not a proof.

core · Beck and Fowler, in Fowler 1999. Anti-patterns: → Design patterns: "Anti-pattern and code smell: the difference".

Front

Code smell and bug: the difference

Back

A bug makes the program behave wrongly now. A smell leaves the behaviour right but makes the code harder to read and change, so later changes cost more and are more likely to bring bugs in.

core · Tip: removing a smell is refactoring, fixing a bug changes behaviour; keep the two in separate steps.

Front

Code smells: how teams find them

Back

In code review, whenever a change turns out harder than it should be, and with static analysis tools that flag the measurable ones, such as method length, parameter count or copied blocks. Smells like feature envy or divergent change mostly need a human reader.

core · Static analysis: → Software testing, Reviews and quality.

Front

Static analysis flags a 60-line method that copies 40 fields of a fixed file layout into a record, one per line: what to do

Back

Probably nothing: the method is long but flat, and each line is obvious. Splitting it would scatter one simple mapping over several methods. A smell asks for a judgement, not an automatic fix.

core

Construction

301 cards

Front

Software construction: definition

Back

The programmers' share of building software: turning a design into code that runs, with the debugging, checking and testing of single units and of their combination that goes with it, and later changes to that code. Much detailed design, such as classes and algorithms, is decided along the way.

core · SWEBOK v4.0a, ch. 4. Where design stops and testing starts varies with the process model.

Front

A HashMap for a station's compartments, the split into booking and billing services, and a test team's system test of the booking flow: which of them is construction

Back

The HashMap: a detailed choice a programmer makes while writing the code. Splitting the system into services is architectural design, usually settled before construction starts, and testing the integrated system as a whole is system testing, an activity of its own.

core · → Design principles: "Detailed design: definition".

Front

Error code (error handling): definition

Back

A special return value, such as -1, false or a status number, that a routine returns in place of its normal result to say that it failed, leaving the caller to test for it.

core · C's standard library and most operating-system calls report failures this way.

Front

sendReminder(phone) returns false when the SMS gateway is down, and the clinic's nightly job never looks at the result: what happens

Back

The failure vanishes: the job carries on and reports success, patients get no reminder and nobody learns why. An error code helps only if the caller checks it, and nothing makes the caller check.

core · Tip: static analysis can flag ignored results, as Error Prone's CheckReturnValue check does.

Practice

17 cards

Front

Exercise 1: Check-in at a youth hostel

Hostel Seeblick checks guests in at its front desk with the code below. Three groups of people ask for changes to it. The front desk sets the rules for dormitory beds. The city changes its tourist tax about once a year; the latest change added a reduced rate for youth-card holders aged 18 or over. The hostel's marketing team redesigns the receipt every season and now wants a text-message receipt as well. Callers pass receiptMode as 1 to print the receipt, 2 to e-mail it and 3 for both. Housekeeping frees a bed once it has been stripped.

import java.time.LocalDate;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

record Guest(String name, String email, int age, String category) {}

class BedBook {
    private static final BedBook INSTANCE = new BedBook();
    private final Map<String, Integer> freeBeds = new HashMap<>();
    private BedBook() { }
    static BedBook instance() { return INSTANCE; }
    Map<String, Integer> freeBeds() { return freeBeds; }
}

class MailServer {
    MailServer(String host) { }
    void send(String to, String subject, String body) { System.out.println("mail to " + to + ": " + subject); }
}

class CheckInDesk {
    String checkIn(Guest guest, String dorm, int nights, int receiptMode) {
        Map<String, Integer> beds = BedBook.instance().freeBeds();
        int free = beds.getOrDefault(dorm, 0);
        if (free < 1) return "full";
        beds.put(dorm, free - 1);

        int taxCents;
        switch (guest.category()) {
            case "school group": taxCents = 0; break;
            case "youth": taxCents = guest.age() < 18 ? 0 : 150 * nights; break;
            default: taxCents = 250 * nights;
        }

        String receipt = "Hostel Seeblick, " + LocalDate.now() + "\n" + guest.name() + ", "
            + dorm + ", nights: " + nights + "\nCity tax: "
            + String.format(Locale.GERMANY, "%d,%02d EUR", taxCents / 100, taxCents % 100);
        if (receiptMode != 2) System.out.println(receipt);
        if (receiptMode >= 2)
            new MailServer("mail.seeblick.example").send(guest.email(), "Your stay", receipt);
        return "ok";
    }
}

class Housekeeping {
    void bedStripped(String dorm) {
        BedBook.instance().freeBeds().merge(dorm, 1, Integer::sum);
    }
}
1.

1.1 Which two kinds of coupling on the classic scale does the listing show, and where? (2 points)

2.

1.2 Which reasons to change does CheckInDesk have, who asks for each, and which principle does that break? (3 points)

3.

1.3 Which two further SOLID principles does checkIn break, and how does each show in the code? (2 points)

4.

1.4 Redesign the cluster: name the classes and interfaces, what each owns, and which way the dependencies run. (4 points)

Back

1.

1.1 Which two kinds of coupling on the classic scale does the listing show, and where? (2 points)

2 points: common coupling: CheckInDesk and Housekeeping both change the one map that the singleton BedBook hands to any caller, global data behind a method call that no class guards (1) · control coupling: the number receiptMode tells checkIn which of its branches to run, so every caller must know what 1, 2 and 3 do inside it (1)

Model answer:

  • Common coupling: BedBook.instance().freeBeds() hands every caller the same mutable map. CheckInDesk takes beds from it and Housekeeping gives them back, though neither names the other, and any other class could write to it too, so a wrong bed count can't be traced to one owner. The singleton hides a global variable; it doesn't remove it.
  • Control coupling: receiptMode is a code that picks paths inside checkIn. The caller has to know that 3 means both, and the method reads it through != 2 and >= 2, which a fourth mode would break.
2.

1.2 Which reasons to change does CheckInDesk have, who asks for each, and which principle does that break? (3 points)

3 points: the bed rules, asked for by the front desk, and the tourist tax, asked for by the city (1) · the receipt's layout and channels, asked for by marketing, so the requests of three groups all land in checkIn (1) · the single responsibility principle: a new tax rate or a text-message receipt means editing and retesting the method that hands out beds (1)

Model answer: Three groups drive changes to the one method: the front desk with its rules for beds, the city with its tax rules, and marketing with the receipt's layout and the ways it is sent. The mail host, which IT might move, is a fourth candidate. The class answers to several actors, against the single responsibility principle: marketing's text-message receipt is an edit to the code that decides whether a guest gets a bed, and a slip in it can stop check-ins.

3.

1.3 Which two further SOLID principles does checkIn break, and how does each show in the code? (2 points)

2 points: open–closed: each new guest category or tax rate means another case in the switch inside checkIn, an edit to working code rather than a new class or table entry (1) · dependency inversion: the check-in policy creates the concrete MailServer, with its host name, itself, so it depends on a technical detail, and a test of checkIn would send real mail (1)

Model answer:

  • Open–closed: the tax rules change every year, and each change edits the switch in checkIn, so the whole method has to be retested every time.
  • Dependency inversion: new MailServer("mail.seeblick.example") sits inside the code that decides what a check-in does. A text-message receipt adds another concrete class to the same method, and no test can swap the mail for a fake.
4.

1.4 Redesign the cluster: name the classes and interfaces, what each owns, and which way the dependencies run. (4 points)

4 points: a class such as BedRegister owns the free beds, with operations such as take(dorm) and release(dorm) that the desk and housekeeping both call, and no class hands out the map any more (1) · the tax moves out of checkIn, for example into a TouristTax that keeps one rule per category in a map, so that a new category is a new entry (1) · the receipt's text in a class of its own, and the channels behind an interface such as ReceiptChannel, declared beside the desk, with printed, e-mail and text-message implementations (1) · CheckInDesk gets the register, the tax and the channels through its constructor or the call, names no concrete channel and no mode number, and only the start-up code wires the concrete classes (1)

Model answer: For example:

  • BedRegister: owns the bed counts, with boolean take(String dorm) and void release(String dorm). CheckInDesk and Housekeeping both call it, and no other class sees the map.
  • TouristTax: int cents(Guest guest, int nights), which looks up the rule for the guest's category in a map from category to rule. The city's next rate is one more entry, tested on its own.
  • Receipt: builds the text from the guest, the stay and the tax; marketing's layout changes stay here.
  • ReceiptChannel: an interface owned by the check-in code, void send(Guest guest, String receipt), with PrintedReceipt, MailedReceipt, which holds the MailServer, and later TextReceipt.
  • CheckInDesk: gets a BedRegister, a TouristTax and a Receipt through its constructor; checkIn(guest, dorm, nights, channels) takes the channels the guest chose, so the mode number goes.

The desk depends on these abstractions, and MailedReceipt depends on MailServer, never the reverse. Only the code that starts the application, the composition root, names the concrete classes.

Front

Exercise 2: Heating in a block of flats

A housing co-operative controls the heating of every room in its flats through RoomHeating. The tenants' app calls setTarget(wanted) with the tenant's choice and then shows "Set to X °C", with X the value it asked for. An energy report counts rooms by their target in an int[19], one slot for each degree from 10 to 28, with count[room.target() - 10]++. Five subclasses have been written for special rooms. In NightHeating, the building system sets night to true from 22:00 to 06:00.

/** Heating of one room. Invariant: 10 <= target() <= 28. */
class RoomHeating {
    protected int target = 20;

    /** Requires 10 <= celsius <= 28. Afterwards target() returns celsius. */
    void setTarget(int celsius) {
        if (celsius < 10 || celsius > 28) throw new IllegalArgumentException("target out of range: " + celsius);
        target = celsius;
    }

    int target() { return target; }

    /** Returns 0 when roomCelsius >= target(), otherwise a power above 0. */
    int powerWatts(double roomCelsius) { return roomCelsius >= target ? 0 : 1500; }
}

class TolerantHeating extends RoomHeating {
    @Override void setTarget(int celsius) { super.setTarget(Math.max(10, Math.min(28, celsius))); }
}

class EcoHeating extends RoomHeating {
    @Override void setTarget(int celsius) { super.setTarget(Math.min(celsius, 21)); }
}

class NightHeating extends RoomHeating {
    boolean night;
    @Override void setTarget(int celsius) {
        if (night && celsius > 18) throw new IllegalStateException("night limit is 18");
        super.setTarget(celsius);
    }
}

class SaunaHeating extends RoomHeating {
    @Override void setTarget(int celsius) {
        if (celsius < 10 || celsius > 90) throw new IllegalArgumentException("target out of range: " + celsius);
        target = celsius;
    }
}

class QuietHeating extends RoomHeating {
    @Override int powerWatts(double roomCelsius) { return roomCelsius >= target ? 0 : 800; }
}
1.

2.1 For each of the five subclasses, say whether it can stand in for RoomHeating, and which part of the contract it keeps or breaks. (5 points)

2.

2.2 Which of the two clients goes wrong with which subclass, and how? (2 points)

3.

2.3 Change the design so that the eco limit no longer breaks substitution. (2 points)

4.

2.4 Suppose setTarget in RoomHeating ends with assert checks of its postcondition and of the class invariant. Which of the subclasses' breaches from 2.1 would a run with -ea catch? (1 point)

Back

1.

2.1 For each of the five subclasses, say whether it can stand in for RoomHeating, and which part of the contract it keeps or breaks. (5 points)

5 points: TolerantHeating can: it accepts more, a weaker precondition, and for every value from 10 to 28 still sets exactly that value, within the invariant (1) · EcoHeating can't: for a valid 24 it sets 21, so target() no longer returns celsius, a weaker postcondition (1) · NightHeating can't: at night it refuses 19 to 28, which the base accepts, a stronger precondition (1) · SaunaHeating can't: it lets target() reach 90 and so breaks the class invariant, although a wider range on its own would be an allowed weaker precondition (1) · QuietHeating can: 800 W is still more than 0 below the target, and it returns 0 at or above it, so powerWatts keeps its postcondition (1)

Model answer:

  • TolerantHeating: substitutable. Values outside 10–28 were the caller's mistake under the base contract; clamping them is extra tolerance. Any call that meets RoomHeating's precondition sets exactly the requested target, and target() stays within 10–28.
  • EcoHeating: not substitutable. setTarget(24) meets the precondition, yet target() returns 21 afterwards: the override delivers less than the postcondition promises.
  • NightHeating: not substitutable. From 22:00 a call with 22 throws, though the base contract accepts it, so callers must now meet a condition the supertype never stated.
  • SaunaHeating: not substitutable. Accepting more would be allowed, but the extra values end up in target(), outside the invariant that every RoomHeating keeps.
  • QuietHeating: substitutable. The contract promises only "0 at or above the target, more than 0 below", and 800 W keeps that promise.
2.

2.2 Which of the two clients goes wrong with which subclass, and how? (2 points)

2 points: the tenants' app shows "Set to 24 °C" for an EcoHeating room that is set to 21, and gets an IllegalStateException from NightHeating at night for any choice from 19 to 28 (1) · the energy report fails with an ArrayIndexOutOfBoundsException for a sauna set above 28, at index 70 for 80 °C (1)

Model answer: Run against each subclass with a choice of 24:

  • The app: with EcoHeating, it shows "Set to 24 °C" while target() returns 21, and nothing anywhere reports the difference. With NightHeating at night, choosing 22 throws IllegalStateException: night limit is 18, an exception the app has no reason to expect from a valid target.
  • The energy report: a sauna set to 80 makes it compute count[70] in an array of 19 and fail with ArrayIndexOutOfBoundsException: Index 70 out of bounds for length 19. The report relied on the invariant, not on any method's postcondition.

TolerantHeating and QuietHeating break neither client.

3.

2.3 Change the design so that the eco limit no longer breaks substitution. (2 points)

2 points: a design in which no subclass weakens the postcondition, such as a query maxTarget() in the base contract, 28 in RoomHeating and 21 in EcoHeating, with the postcondition target() = min(celsius, maxTarget()), or the eco limit taken out of the hierarchy as a rule that the building system applies before it calls setTarget (1) · the clients follow the new contract: the app shows target() after the call, or the value the rule allows, instead of the value it asked for (1)

Model answer: Either put the limit into the contract every subtype keeps, or take it out of the hierarchy.

  • In the contract: RoomHeating gains int maxTarget(), 28 there and 21 in EcoHeating, and setTarget promises that afterwards target() returns min(celsius, maxTarget()). EcoHeating then keeps the base contract, and the app shows target() after the call, so it reports "Set to 21 °C".
  • Outside the hierarchy: the eco rule becomes a policy, such as TargetPolicy.allowed(room, wanted), that the app applies before calling setTarget. EcoHeating disappears, and every RoomHeating keeps the old contract.
4.

2.4 Suppose setTarget in RoomHeating ends with assert checks of its postcondition and of the class invariant. Which of the subclasses' breaches from 2.1 would a run with -ea catch? (1 point)

1 point: none: EcoHeating hands 21 to super.setTarget, so the check compares 21 with 21; NightHeating throws before the base's code runs; SaunaHeating never calls super.setTarget, so its 80 is never checked; the base's assertions test only the base's own code

Model answer: None of them, as a run with -ea confirms. The checks at the end of the base's setTarget:

target = celsius;
assert Integer.valueOf(target).equals(celsius) : "postcondition";
assert 10 <= target && target <= 28 : "invariant";
  • EcoHeating turns 24 into 21 before it calls super.setTarget(21), so the postcondition check sees celsius and target both at 21.
  • NightHeating throws its IllegalStateException before the base's code runs, so there is nothing to check.
  • SaunaHeating overrides setTarget without calling super, so the checks never run, and target() returns 80.

Java doesn't carry a contract into overrides. Each override needs checks of its own, or tests that run every subclass against the base contract.

Front

Exercise 3: Measuring a ferry booking desk

A ferry company books vehicles onto its crossings with the seven types below. Count among these seven only, by these rules:

  • A class uses another when it calls one of its methods or its constructor, or names it as a field, parameter or return type. A record's accessor counts as one of the record's methods.
  • Fan-out counts the classes a class uses; fan-in counts the classes that use it.
  • CBO counts the classes a class uses or is used by, each once.
  • LCOM is the Chidamber–Kemerer value of 1994: P, the pairs of methods that share no field of the class, minus Q, the pairs that share at least one; LCOM is 0 when Q is the larger. For BookingDesk, count its five methods and its five fields.
import java.util.ArrayList;
import java.util.List;

record Vehicle(String plate, int lengthCm, boolean hazardous) {}
record Crossing(String route, int laneMetres) {}
record Booking(Vehicle vehicle, Crossing crossing, int priceCents) {}

class Fare {
    int priceCents(Vehicle v, Crossing c) {
        int base = c.route().startsWith("night") ? 1500 : 1800;
        return base + (v.lengthCm() + 99) / 100 * 450 + (v.hazardous() ? 3000 : 0);
    }
}

class DeckPlan {
    private int usedCm;
    boolean fits(Vehicle v, Crossing c) { return usedCm + v.lengthCm() <= c.laneMetres() * 100; }
    void place(Vehicle v) { usedCm += v.lengthCm(); }
}

class Manifest {
    String lines(List<Booking> bookings) {
        StringBuilder sb = new StringBuilder();
        for (Booking b : bookings) sb.append(b.vehicle().plate()).append(b.vehicle().hazardous() ? " HAZ\n" : "\n");
        return sb.toString();
    }
}

class BookingDesk {
    private final Fare fare = new Fare();
    private final DeckPlan deck = new DeckPlan();
    private final List<Booking> bookings = new ArrayList<>();
    private final Manifest manifest = new Manifest();
    private int refundedCents;

    Booking book(Vehicle v, Crossing c) {
        if (!deck.fits(v, c)) return null;
        deck.place(v);
        Booking b = new Booking(v, c, fare.priceCents(v, c));
        bookings.add(b);
        return b;
    }
    int quote(Vehicle v, Crossing c) { return fare.priceCents(v, c); }
    String manifestText() { return manifest.lines(bookings); }
    void refund(int cents) { refundedCents += cents; }
    int refundedToday() { return refundedCents; }
}
1.

3.1 Give the fan-in and fan-out of each class. (3 points)

2.

3.2 Give the CBO of Manifest and of BookingDesk. (2 points)

3.

3.3 Compute the LCOM of BookingDesk. Which split lowers it, and to what? (3 points)

4.

3.4 What do the numbers suggest about Vehicle and BookingDesk, and what don't they tell you? (2 points)

Back

1.

3.1 Give the fan-in and fan-out of each class. (3 points)

3 points: Vehicle fan-in 5 and fan-out 0, Crossing fan-in 4 and fan-out 0 (1) · Booking fan-in 2 and fan-out 2; Fare, DeckPlan and Manifest each fan-in 1 and fan-out 2, Manifest using Vehicle because b.vehicle().plate() calls a method of Vehicle (1) · BookingDesk fan-in 0 and fan-out 6: Fare, DeckPlan, Manifest, Booking, Vehicle and Crossing (1)

Model answer: Fan-in first, then fan-out:

  • Vehicle: 5, 0. Used by Booking, Fare, DeckPlan, Manifest and BookingDesk.
  • Crossing: 4, 0. Used by Booking, Fare, DeckPlan and BookingDesk.
  • Booking: 2, 2. Uses Vehicle and Crossing; used by Manifest and BookingDesk.
  • Fare and DeckPlan: 1, 2 each. Each uses Vehicle and Crossing and is used by BookingDesk.
  • Manifest: 1, 2. Uses Booking and Vehicle; used by BookingDesk.
  • BookingDesk: 0, 6. Uses all the others.

Manifest never names Vehicle, but it calls plate() and hazardous() on one, so it depends on it all the same.

2.

3.2 Give the CBO of Manifest and of BookingDesk. (2 points)

2 points: Manifest 3: Booking and Vehicle, which it uses, and BookingDesk, which uses it (1) · BookingDesk 6, the six classes it uses, since none of the seven uses it (1)

Model answer: CBO joins both directions and counts each class once. Manifest is coupled to Booking and Vehicle, which it uses, and to BookingDesk, which uses it: 3. BookingDesk uses all six others, and none of them uses it: 6.

3.

3.3 Compute the LCOM of BookingDesk. Which split lowers it, and to what? (3 points)

3 points: of the 10 pairs of methods, 3 share a field: book and quote share fare, book and manifestText share bookings, refund and refundedToday share refundedCents; so P = 7, Q = 3 and LCOM = 4 (1) · refund, refundedToday and refundedCents share nothing with the rest, so they move into a class of their own, such as RefundLedger (1) · BookingDesk then has three methods with P = 1 and Q = 2, so LCOM 0, and the new class has LCOM 0 as well (1)

Model answer: The fields each method uses: book uses deck, fare and bookings; quote uses fare; manifestText uses manifest and bookings; refund and refundedToday use refundedCents. Of the 10 pairs, three share a field, so Q = 3 and P = 7, and LCOM = 7 − 3 = 4.

The two refund methods form a group with their own field that touches nothing else. Moved with refundedCents into a RefundLedger, they leave BookingDesk with book, quote and manifestText: two pairs share a field and one doesn't, so P = 1, Q = 2 and LCOM = 0. The ledger's one pair shares its field, so its LCOM is 0 too.

4.

3.4 What do the numbers suggest about Vehicle and BookingDesk, and what don't they tell you? (2 points)

2 points: Vehicle's fan-in of 5 makes it the class whose changes reach furthest, such as lengths in metres instead of centimetres, so it should change rarely and have thorough tests; BookingDesk's fan-out of 6 means that changes in six classes can reach it (1) · the counts don't say whether a dependency is a problem: BookingDesk coordinates a booking, so a high fan-out is its job, while the refunds are the real misfit, which LCOM showed and CBO didn't (1)

Model answer: Vehicle is used by five of the seven classes, so storing the length in metres, say, ripples through all of them; it should change rarely and have thorough tests. BookingDesk depends on everything, so it breaks most easily when others change. That is expected of a class that coordinates a booking: it calls the fare, the deck plan and the manifest by design. The counts pick out classes worth a closer look; whether one is badly designed takes reading it. Here the cohesion count found the real problem, refunds that have nothing to do with booking.

Front

Exercise 4: Lending lab equipment

A university's electronics lab lends devices such as soldering stations and oscilloscopes to students. A student may borrow a device only with the safety certificate that its model requires and with no fines open. The loan desk runs the code below.

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

record Training(List<String> certificates) {}
record Account(List<Integer> openFinesCents) {}
record DeviceModel(String name, String safetyClass, int loanDays) {}

class Student {
    private final Training training = new Training(new ArrayList<>());
    private final Account account = new Account(new ArrayList<>());
    private final List<Device> loans = new ArrayList<>();
    Training getTraining() { return training; }
    Account getAccount() { return account; }
    List<Device> getLoans() { return loans; }
}

class LoanStatus {
    private boolean onLoan;
    private LocalDate due;
    boolean isOnLoan() { return onLoan; }
    void setOnLoan(boolean onLoan) { this.onLoan = onLoan; }
    void setDue(LocalDate due) { this.due = due; }
}

class Device {
    private final DeviceModel model;
    private final LoanStatus status = new LoanStatus();
    Device(DeviceModel model) { this.model = model; }
    DeviceModel getModel() { return model; }
    LoanStatus getStatus() { return status; }
}

class LoanDesk {
    String lend(Student s, Device d, LocalDate today) {
        if (!s.getTraining().certificates().contains(d.getModel().safetyClass())) return "training missing";
        if (!s.getAccount().openFinesCents().isEmpty()) return "fines open";
        if (d.getStatus().isOnLoan()) return "already lent";
        LocalDate due = today.plusDays(d.getModel().loanDays());
        d.getStatus().setOnLoan(true);
        d.getStatus().setDue(due);
        s.getLoans().add(d);
        return "due " + due;
    }
}
1.

4.1 Which calls in lend break the Law of Demeter, and which are allowed? (2 points)

2.

4.2 Besides the Law of Demeter, what goes wrong with how lend changes the device and the student, and what can it lead to? (2 points)

3.

4.3 Rewrite lend so that it asks each object to do its own part, and name the methods you add. (3 points)

Back

1.

4.1 Which calls in lend break the Law of Demeter, and which are allowed? (2 points)

2 points: the calls on objects that another call returned break it: certificates().contains(…) on the student's training, safetyClass() and loanDays() on the device's model, openFinesCents().isEmpty() on the student's account, isOnLoan(), setOnLoan(…) and setDue(…) on the device's status, and add(d) on the student's own list of loans (1) · allowed: getTraining(), getAccount(), getLoans(), getModel() and getStatus() on the parameters s and d, and plusDays(…) on the parameter today (1)

Model answer: lend may call methods on itself, its parameters s, d and today, and objects it creates. Calls on what those calls return go further:

  • Breaking it: getTraining().certificates().contains(…), getModel().safetyClass(), getAccount().openFinesCents().isEmpty(), getStatus().isOnLoan(), getModel().loanDays(), getStatus().setOnLoan(true), getStatus().setDue(due) and getLoans().add(d). Each makes LoanDesk depend on how Student and Device are built inside.
  • Allowed: the first call of each chain, on s or d, and today.plusDays(…), a call on a parameter.
2.

4.2 Besides the Law of Demeter, what goes wrong with how lend changes the device and the student, and what can it lead to? (2 points)

2 points: it asks for the objects' data and changes them from outside, against tell, don't ask: the rule that a lent device has a due date lives in LoanDesk, which sets the two fields one at a time (1) · any other class can do the same and skip a step, such as marking a device as lent without a due date or adding a device to a student's loans without lending it, because Student and Device hand out their insides (1)

Model answer: LoanDesk reads the device's status, decides, and then writes the status field by field; it also adds to a list that Student hands out. The rules of lending live outside the objects they are about, so nothing keeps them together. A second piece of code, such as a reservation screen, can set onLoan and forget the due date, or put a device on a student's list without lending it, and neither class can stop it. Encapsulation is lost: getLoans() and getStatus() give away mutable insides.

3.

4.3 Rewrite lend so that it asks each object to do its own part, and name the methods you add. (3 points)

3 points: Student answers isTrainedFor(device) and hasOpenFines() itself, by asking its training and its account in turn, so lend no longer reaches into them (1) · Device lends itself: one method checks that it isn't lent, computes the due date from its model and records both on its status in one step, returning the due date or saying it can't (1) · lend calls only methods of s and d and gives the same results for the four outcomes, and Student records the loan itself, with no list handed out (1)

Model answer:

class LoanDesk {
    String lend(Student s, Device d, LocalDate today) {
        if (!s.isTrainedFor(d)) return "training missing";
        if (s.hasOpenFines()) return "fines open";
        Optional<LocalDate> due = d.lend(today);
        if (due.isEmpty()) return "already lent";
        s.recordLoan(d);
        return "due " + due.get();
    }
}

The methods it relies on:

  • Student.isTrainedFor(Device d) returns training.covers(d.safetyClass()), with Training.covers(String) checking its own list;
  • Student.hasOpenFines() asks account.hasOpenFines();
  • Student.recordLoan(Device d) adds to its private list, and getLoans() goes;
  • Device.safetyClass() returns model.safetyClass();
  • Device.lend(LocalDate today) returns an empty Optional if the device is already lent; otherwise it computes today.plusDays(model.loanDays()), calls status.lend(due), which sets both fields at once, and returns the date.

The four outcomes are unchanged. The Optional and the LocalDate are values handed back to lend, not collaborators it navigates through.

Licence: Personal use Report this deck

New Software engineering decks by email

Hear when they arrive, or tell us which deck you need.

Comments

Loading comments…