Module 8 · 12 marks · Design, criticality & testing
Object-oriented design, UML & design evolution
Object-oriented design structures a system as interacting objects that hide their own state. Good designs follow an architecture, keep coupling low and cohesion high, reuse proven design patterns and evolve easily: new features become new classes rather than edits to old ones.
Think of a well-run housing office. Each counter (object) has one job, keeps its own files locked in its drawer (encapsulation) and is approached only through its window (interface). Counters pass slips to each other, never rummaging in another's drawer (low coupling). When a new scheme arrives, you open a new counter instead of rebuilding the office (design evolution). Proven office layouts — a reception that notifies every department, a single records room — are the design patterns.
Design evolution: encapsulation and loose coupling let new objects (e.g. Sommerville's AirQuality for the weather station) be added with little impact; refactoring preserves behaviour.
01Objects, classes and the OOD process
Object-oriented design (OOD) builds a system out of cooperating objects. Each object keeps its own state private and offers operations that are the only way to read or change it (encapsulation). Objects get work done by calling one another's operations (message passing). A class is the definition — the template — from which objects are created. Object-oriented analysis models the problem domain, OOD models the software solution, and object-oriented programming implements it in a language such as Java or C++.
Because objects are self-contained, OO systems are easier to change: an object can be modified or replaced without touching others as long as its interface stays the same; objects that model real-world entities (Applicant, Scheme, LoanAccount) are easy to understand; and well-designed objects are reusable. The price is more up-front design effort, and run-time overheads that can matter in some embedded systems.
Sommerville's object-oriented design process
Understand and define the context and external interactions
Model the relationships between the software and its environment: a context model plus a use-case model of the interactions (apply, scrutinise, sanction, pay EMI, run draw).
Design the system architecture
Identify the major components and how they interact, choosing architectural patterns (layered, client–server, MVC).
Identify the principal system objects
Find the key classes from the domain: Applicant, Application, Scheme, Unit, LoanAccount, Instalment, Payment.
Develop design models
Produce static models (class, package/sub-system) and dynamic models (sequence, state machine) at the right level of detail.
Specify object interfaces
Define the operations and parameters each object or component offers, so they can be implemented and tested in parallel.
Static (structural) models
Describe the static structure: classes and their relationships
Class diagrams — generalisation, association, aggregation, composition
Sub-system / package models — logical groupings of classes
Component and deployment diagrams
Dynamic models
Describe the run-time structure and interactions between objects
Sequence diagrams — the order of service requests between objects
State machine diagrams — how an object changes state in response to events
Activity and communication diagrams
PSC favourite
Order to remember: context & interactions → architecture → principal objects → design models → object interfaces. In practice the activities interleave and inform each other, but exam questions use this order.
02Architectural design and architectural patterns
Architectural design decides which major sub-systems the system is made of and how they are controlled and communicate with one another; its output is the software architecture. It is the first, most influential design decision, because non-functional properties are shaped by it: performance (localise critical operations, minimise communication), security (critical assets in inner layers), safety (safety-critical features in a few sub-systems), availability (redundant components) and maintainability (fine-grained, replaceable components).
Pattern
Organisation
Used when
Advantages
Disadvantages
Layered
Functionality in layers; each layer uses only the services of the layer below (UI → business logic → data access → DBMS)
Building on existing systems; multi-level security; separating concerns in business applications
A layer can be replaced without affecting others; portability
Clean separation is hard in practice; layer crossing costs performance
Repository
All data held in a central repository; components interact only through it
Large volumes of shared data — IDEs, CASE toolsets, MIS
Components independent; data managed consistently in one place
Single point of failure; all traffic through the repository; hard to distribute
Client–server
Functions offered as services by separate servers; clients request them over a network
A shared database accessed from many places; varying load
Servers can be distributed; general services available to all clients
Each service is a point of failure; performance depends on the network
Pipe and filter
Data flows through a chain of filters, each transforming its input
Batch data processing, compilers, Unix pipelines, signal processing
Easy to understand and reuse; easy to add a transformation
All filters must agree a data format; poor for interactive systems
MVC
Model (data and logic), View (presentation), Controller (handles input, updates model, selects view)
Several views of the same data; interaction requirements that change often
Data and presentation change independently; multiple views
Extra code and complexity for simple models
TextHLAMS architecture: client–server overall, layered on the server, MVC at the top
Browser / mobile app (client) <- View
| HTTPS
+--------v-----------------------------------------+
| Presentation layer: controllers, page templates | <- Controller + View
+--------------------------------------------------+
| Business layer: LoanService, AllotmentService, | <- Model (logic)
| PaymentService, EligibilityRules |
+--------------------------------------------------+
| Data-access layer: repositories (DAOs) | <- Model (data)
+--------------------------------------------------+
| DBMS + document store |
+--------------------------------------------------+
Each layer calls only the layer below; adapters connect the
business layer to banks, the payment gateway and the SMS gateway.
MVC was devised by Trygve Reenskaug at Xerox PARC in 1979 for Smalltalk and now underlies web frameworks such as Spring MVC and ASP.NET MVC. Real systems combine patterns: HLAMS is client–server overall, layered inside the server, MVC in the presentation layer, uses the database as a repository, and runs its nightly bank-file job as a pipe and filter — read → validate → match → post → report.
PSC favourite
PSC 2023: MVC = Model–View–Controller. The model holds data and business rules, the view renders it, and the controller turns user input into operations on the model.
03Identifying objects and developing design models
Identifying the right object classes is the hardest part of OOD; there is no magic formula, and the first set of classes is always refined. Proven approaches can be combined:
Grammatical analysis (Abbott, 1983) — in a natural-language description, nouns suggest objects and attributes, verbs suggest operations.
Tangible things in the domain — physical things (flat, document), roles (clerk, officer), events (allotment draw), interactions (payment), locations (district office), organisational units (scheme section).
Behavioural approach — understand the overall behaviour, then find which objects initiate and take part in each behaviour.
Scenario-based analysis — walk through each use-case scenario and record the objects, attributes and operations it needs.
CRC cards (Class–Responsibility–Collaborator; Beck and Cunningham, 1989) — one index card per class listing what it knows and does, and which classes it works with.
Noun in the description
Candidate
Verb in the description
Candidate operation
applicant
class Applicant
submits (an application)
Application.submit()
application
class Application
scrutinises
Application.scrutinise()
scheme
class Scheme
sanctions (a loan)
LoanService.sanction()
document
class Document (part of Application)
computes (the EMI)
LoanAccount.computeEmi()
loan
class LoanAccount
posts (a payment)
PaymentService.post()
EMI, principal, rate, tenure
attributes of LoanAccount
notifies (the applicant)
Notifier.statusChanged()
Grammatical analysis of: 'An applicant submits an application for a scheme with documents; a clerk scrutinises it; an officer sanctions a loan whose EMI is computed from principal, rate and tenure; payments from banks are posted; the applicant is notified at each step.'
Design models then show the objects and their relationships. Sub-system (package) models group classes into packages — portal, loans, allotment, payments, notify, common — with dependencies that should not form cycles. Sequence models show the interaction for each use case, and state machine models are drawn only for objects with interesting life cycles, such as Application and LoanAccount. Finally, interface specifications define what each component offers, without revealing how:
JavaAn interface specification for the loan component: clients depend on this, not on the implementation
public interface LoanService {
/** Records a new application and returns its number, e.g. "A-2026-1234". */
String submit(String applicantId, String schemeCode, long requestedAmount);
/** Marks an application as sanctioned and creates its loan account. */
void sanction(String applicationNo, String officerId);
/** Equated monthly instalment in rupees, rounded to the nearest rupee. */
long emi(long principal, double annualRatePct, int months);
/** Current status, e.g. "UNDER_SCRUTINY". */
String status(String applicationNo);
}
04Design principles: abstraction, modularity, information hiding, SOLID
Abstraction means concentrating on what matters at the current level and ignoring detail. Pressman names three kinds: procedural abstraction (a named sequence of instructions with one function, e.g. computeEmi()), data abstraction (a named collection of data describing an object, e.g. LoanAccount) and control abstraction (a control mechanism used without its internals, e.g. an iterator or a semaphore). Its partner is stepwise refinement (Niklaus Wirth, 1971): start from a high-level statement and elaborate it step by step.
Modularity divides software into separately named, addressable components that are integrated to meet the requirements; Myers called it the single attribute that makes a program intellectually manageable. Cost per module falls as the number of modules grows, but integration cost rises, so there is a region of minimum total cost — both under- and over-modularisation are bad. Information hiding (David Parnas, 1972) says each module should hide the design decisions most likely to change — its data structures and algorithms — behind a stable interface. The result is functional independence: single-minded modules with little interaction, measured by cohesion and coupling.
Principle
Statement
HLAMS example
S — Single Responsibility
A class should have only one reason to change
Keep EmiCalculator separate from ReceiptPrinter; LoanAccount should not also format PDFs
O — Open–Closed (Bertrand Meyer, 1988)
Open for extension, closed for modification
Add a new InterestStrategy class instead of editing a switch on scheme type
L — Liskov Substitution (Barbara Liskov, 1987)
Objects of a subtype must be usable wherever the base type is expected, without breaking correctness
A GovtEmployeeApplicant must satisfy every contract of Applicant — e.g. never throw from getIncome()
I — Interface Segregation
Clients should not be forced to depend on methods they do not use
Split a fat BankService into PaymentGateway and StatementReader
D — Dependency Inversion
High-level modules depend on abstractions, not on low-level details
LoanService depends on a Notifier interface, not on a concrete SmsSender class
SOLID — collected by Robert C. Martin around 2000; the acronym was coined by Michael Feathers
Related rules of thumb: DRY (don't repeat yourself — one authoritative place for each rule), KISS (keep it simple), YAGNI (you aren't gonna need it — no speculative features) and the Law of Demeter (talk only to your immediate collaborators; avoid chains like a.getB().getC().doIt()).
PSC favourite
PSC 2026: the principle that reduces interdependence between modules is low coupling, and high cohesion with low coupling makes a system modular and maintainable. PSC 2025: low coupling → minimise dependencies; information hiding means hiding, not exposing, private data.
05Coupling and cohesion
Coupling measures the interdependence between modules — how much one module must know about another. Cohesion measures how strongly the elements inside a module belong together. The classic scales come from Yourdon and Constantine's Structured Design (1979) and Myers. The goal is high cohesion and low coupling: low coupling stops changes rippling through the system; high cohesion makes modules easy to understand, test and reuse.
Rank
Coupling type
Definition
HLAMS example
1 (best)
Data coupling
Modules share only elementary data items passed as parameters
computeEmi(principal, rate, months)
2
Stamp coupling
A whole composite data structure is passed, but only part of it is used
computeEmi(applicationRecord) reading just three fields
3
Control coupling
One module passes a flag that directs the other's internal logic
Modules share an externally imposed data format, protocol or device interface
Two payment modules both tied to a bank's fixed-width file layout
5
Common coupling
Modules share global data
Several modules read and write a global currentInterestRate variable
6 (worst)
Content coupling
One module refers to or modifies the internals of another (its local data, or jumps into its code)
A report module altering LoanAccount's private balance field via reflection
Rank
Cohesion type
Elements are together because…
Example
1 (best)
Functional
All of them contribute to one single, well-defined task
EmiCalculator.computeEmi()
2
Sequential
The output of one element is the input of the next
readBankFile → validateRecords → matchToAccounts
3
Communicational
They operate on the same input data or produce the same output data
printAndArchiveLetter(appNo): both use the same letter data
4
Procedural
They follow a fixed order of execution but work on different data
endOfDay(): close counter, then send SMS batch, then back up logs
5
Temporal
They are related only by when they run
startUp(): open files, reset counters, load configuration, start timers
6
Logical
They do logically similar things; one is chosen by a flag
output(device): screen, printer or PDF selected by a parameter
7 (worst)
Coincidental
No meaningful relationship at all
A 'Utils' class with formatDate(), computeEmi() and sendMail()
Memory aids
Coupling, best → worst: Data, Stamp, Control, External, Common, Content — 'Don't Send Cheap Email, Call Carefully'. Cohesion, best → worst: Functional, Sequential, Communicational, Procedural, Temporal, Logical, Coincidental — 'Fine Software Can Prevent Total Logical Chaos'.
Two structural measures complement them: fan-in — how many modules call a given module (high fan-in signals useful reuse) — and fan-out — how many modules a module calls (high fan-out often signals a module doing too much). The Henry–Kafura information-flow metric combines them, as covered in the project-management topic.
Watch out
Books differ in detail: Rajib Mall lists five coupling types (data, stamp, control, common, content) and omits external; some lists add message coupling (lowest of all) for OO systems. The order of the shared types never changes — data is best and content worst; functional is best and coincidental worst.
06Design patterns: the Gang of Four catalogue
A design pattern captures a problem that keeps recurring and the core idea of a solution to it, in a form that can be reapplied in many different programs. It is not a finished design or a code library; it records experience that designers adapt to each situation. The idea came from the architect Christopher Alexander (A Pattern Language, 1977); Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides — the 'Gang of Four' (GoF) — catalogued 23 patterns in Design Patterns: Elements of Reusable Object-Oriented Software (1994). Every pattern has four essential elements: a name, a problem description, a solution description (a template, not a concrete design) and its consequences (results and trade-offs).
Category
Pattern
Intent in one line
Creational
Abstract Factory
Create families of related objects without naming their concrete classes
Creational
Builder
Build a complex object step by step, separating construction from representation
Creational
Factory Method
Define an interface for creating an object, but let subclasses decide which class to instantiate
Creational
Prototype
Create new objects by cloning a prototypical instance
Creational
Singleton
Ensure a class has only one instance, with a global point of access
Structural
Adapter
Convert a class's interface into the interface its clients expect
Structural
Bridge
Decouple an abstraction from its implementation so both can vary independently
Structural
Composite
Compose objects into trees so single objects and groups are treated uniformly
Structural
Decorator
Attach extra responsibilities to an object dynamically — an alternative to subclassing
Structural
Facade
Offer one simple interface to a complex sub-system
Structural
Flyweight
Share large numbers of fine-grained objects efficiently
Structural
Proxy
Provide a stand-in that controls access to another object
Behavioural
Chain of Responsibility
Pass a request along a chain of handlers until one handles it
Behavioural
Command
Encapsulate a request as an object, enabling queues, logs and undo
Behavioural
Interpreter
Define a grammar and an interpreter for a simple language
Behavioural
Iterator
Traverse a collection without exposing its representation
Behavioural
Mediator
Centralise how a set of objects interact, so they don't refer to each other directly
Behavioural
Memento
Capture an object's state for later restoration without breaking encapsulation
Behavioural
Observer
When one object changes state, automatically notify all its dependants (one-to-many)
Behavioural
State
Let an object change its behaviour when its internal state changes
Behavioural
Strategy
Define a family of interchangeable algorithms, each encapsulated in its own class
Behavioural
Template Method
Fix an algorithm's skeleton in a method and let subclasses supply some steps
Behavioural
Visitor
Add an operation over an object structure without changing the classes of its elements
PSC 2025: 'design patterns are introduced only during the initial design' is false — patterns are often introduced later, through refactoring, as the design evolves. Counts to remember: 23 = 5 + 7 + 11.
07Six key patterns in code (HLAMS)
Each sample below is a small, self-contained Java fragment from HLAMS. Read the comments for the role each class plays in the pattern.
JavaObserver — Application is the subject; SmsNotifier and AuditLog are observers. A WhatsApp notifier can be added later without touching Application.
import java.util.ArrayList;
import java.util.List;
interface StatusListener {
void statusChanged(String applicationNo, String newStatus);
}
class Application {
private final String applicationNo;
private String status = "SUBMITTED";
private final List<StatusListener> listeners = new ArrayList<>();
Application(String applicationNo) { this.applicationNo = applicationNo; }
void addListener(StatusListener l) { listeners.add(l); }
void setStatus(String newStatus) {
status = newStatus;
for (StatusListener l : listeners) {
l.statusChanged(applicationNo, newStatus); // notify every observer
}
}
}
class SmsNotifier implements StatusListener {
public void statusChanged(String no, String s) {
System.out.println("SMS: application " + no + " is now " + s);
}
}
class AuditLog implements StatusListener {
public void statusChanged(String no, String s) {
System.out.println("AUDIT: " + no + " -> " + s);
}
}
public class ObserverDemo {
public static void main(String[] args) {
Application a = new Application("A-2026-1234");
a.addListener(new SmsNotifier());
a.addListener(new AuditLog());
a.setStatus("SANCTIONED"); // both observers print a line
}
}
JavaSingleton — one shared configuration object. The private constructor stops other classes from calling new.
public final class AppConfig {
private static final AppConfig INSTANCE = new AppConfig(); // created once
private final double defaultRate;
private AppConfig() {
defaultRate = 9.0; // in practice, read from a file or database
}
public static AppConfig getInstance() { return INSTANCE; }
public double getDefaultRate() { return defaultRate; }
}
// usage: double r = AppConfig.getInstance().getDefaultRate();
JavaFactory Method — SchemeOffice uses a Scheme without knowing its class; each subclass decides which Scheme to create.
interface Scheme {
long maxLoan();
}
class LigScheme implements Scheme { public long maxLoan() { return 1000000; } }
class MigScheme implements Scheme { public long maxLoan() { return 2500000; } }
abstract class SchemeOffice { // the creator
abstract Scheme createScheme(); // the factory method
String describe() {
Scheme s = createScheme(); // product used through its interface
return "Maximum loan: Rs " + s.maxLoan();
}
}
class LigOffice extends SchemeOffice { Scheme createScheme() { return new LigScheme(); } }
class MigOffice extends SchemeOffice { Scheme createScheme() { return new MigScheme(); } }
JavaAdapter — HLAMS expects PaymentGateway; the bank's existing API cannot be changed, so BankAdapter converts one interface into the other.
interface PaymentGateway { // what HLAMS expects
boolean pay(String loanNo, long amountInPaise);
}
class LegacyBankApi { // existing, incompatible class
int makePayment(String account, double rupees) { // returns 0 on success
System.out.println("Bank paid Rs " + rupees + " to " + account);
return 0;
}
}
class BankAdapter implements PaymentGateway { // the adapter
private final LegacyBankApi bank = new LegacyBankApi();
public boolean pay(String loanNo, long amountInPaise) {
int code = bank.makePayment(loanNo, amountInPaise / 100.0);
return code == 0;
}
}
JavaStrategy — interchangeable EMI algorithms; a loan account can be given a different strategy without changing its own code.
interface InterestStrategy {
double emi(double principal, double annualRatePct, int months);
}
class ReducingBalance implements InterestStrategy {
public double emi(double p, double annualRatePct, int n) {
double r = annualRatePct / 1200;
if (r == 0) return p / n;
double f = Math.pow(1 + r, n);
return p * r * f / (f - 1);
}
}
class FlatRate implements InterestStrategy {
public double emi(double p, double annualRatePct, int n) {
double totalInterest = p * annualRatePct / 100 * n / 12;
return (p + totalInterest) / n;
}
}
class LoanAccount {
private InterestStrategy strategy; // chosen per scheme, swappable
LoanAccount(InterestStrategy s) { strategy = s; }
void setStrategy(InterestStrategy s) { strategy = s; }
double monthlyEmi(double p, double rate, int n) { return strategy.emi(p, rate, n); }
}
JavaDecorator — wrap a charge to add responsibilities at run time. new InsurancePremium(new LatePenalty(new BasicEmi(8997))).amount() = 8997 × 1.02 + 150 = 9326.94
interface Charge {
double amount();
String describe();
}
class BasicEmi implements Charge {
private final double emi;
BasicEmi(double emi) { this.emi = emi; }
public double amount() { return emi; }
public String describe() { return "EMI"; }
}
abstract class ChargeDecorator implements Charge { // is-a Charge and has-a Charge
protected final Charge inner;
ChargeDecorator(Charge inner) { this.inner = inner; }
}
class LatePenalty extends ChargeDecorator {
LatePenalty(Charge c) { super(c); }
public double amount() { return inner.amount() * 1.02; } // +2%
public String describe() { return inner.describe() + " + late penalty"; }
}
class InsurancePremium extends ChargeDecorator {
InsurancePremium(Charge c) { super(c); }
public double amount() { return inner.amount() + 150; }
public String describe() { return inner.describe() + " + insurance"; }
}
08Design evolution, UML design artefacts and design reviews
Sommerville's design evolution argument: a major advantage of OOD is that it simplifies change. Hidden state means an object's internals can change without other objects noticing, and loose coupling means a new object can usually be slotted in while the rest of the system carries on unchanged. In his weather-station case study, pollution monitoring is added by introducing a new class AirQuality at the same level as WeatherData, adding an operation reportAirQuality to WeatherStation, modifying the control software to send pollution readings when the mapping computer asks, and adding objects for the new instruments (NO meter, smoke meter, benzene meter). The existing data-collection objects are not changed.
Evolving HLAMS with minimal impact
Add a WhatsApp alert channel
Write WhatsAppNotifier implements StatusListener and register it. Application, LoanService and the existing notifiers are untouched (Observer + Open–Closed).
Add a step-up EMI plan for young applicants
Write a StepUpEmi strategy class; loan accounts for that scheme receive the new InterestStrategy (Strategy).
Connect a new bank
Write NewBankAdapter implements PaymentGateway; the business layer does not change (Adapter + Dependency Inversion).
Introduce a 'Rental housing' scheme type
Add a RentalScheme class implementing Scheme with its own eligibility rules; code written against the Scheme interface keeps working (polymorphism + Liskov substitution).
Refactor when structure decays
Apply refactorings such as extract class or replace conditional with polymorphism, protected by regression tests, so the design stays changeable.
Encapsulation localises change because data is reached only through operations: storing amounts in paise instead of rupees changes one class. Inheritance lets a new subclass add behaviour without editing tested code, and polymorphism means callers do not change when new subclasses appear. In a function-oriented design with shared global data (common coupling), the same change would ripple into every function that touches that data.
UML design artefact
What it records for HLAMS
Class diagram
Applicant, Application, Scheme, Unit, LoanAccount, Instalment, Payment; associations, compositions, generalisations
Sequence diagrams
'Apply for loan', 'Post bank file', 'Run allotment draw' interactions
Browser/phone → load balancer → two application servers → primary and standby database servers; external nodes for bank, gateway, SMS and e-KYC
Package diagram
portal, loans, allotment, payments, notify, common — dependencies with no cycles
Design reviews examine design documents before coding, when defects are cheapest to fix. Reviewers check that every requirement is traced to a design element, that coupling is low and cohesion high, that interfaces are complete and consistent, that error handling, security and performance budgets are addressed, that the chosen architecture is respected and that the design is testable. Plan-driven projects hold a preliminary (high-level) design review on the architecture and a critical (detailed) design review on component designs; agile teams review continuously through pair programming and code reviews.
PSC favourite
Refactoring = improving the internal structure of code without changing its external behaviour; regression tests make it safe (PSC 2025, 2026).
Worked examples
Try the problem first, then reveal the working one step at a time.
EX 1Identify the coupling
Classify the coupling in each HLAMS fragment and suggest an improvement: (a) arrears(account) where account is a 40-field record but only balance and dueDate are used; (b) generate(type) where type = 'S' produces a sanction letter and 'R' a recovery notice; (c) modules that all read and write a global array pendingApplications; (d) emi(principal, rate, months); (e) a report module that reads LoanAccount's private fields through reflection.
EX 2Identify the cohesion
Classify the cohesion of each module: (a) validateAadhaarFormat() — checks that one ID has a valid format; (b) nightlyJob(): read bank file → validate records → match to accounts, each step feeding the next; (c) init(): open the log file, clear the cache, load scheme masters, start the scheduler; (d) misc: formatDate(), sendMail(), computeEmi(); (e) report(kind): prints the arrears, collection or sanction report depending on kind; (f) applicantSummary(id): computes the outstanding dues and prints the address label from the same applicant record.
EX 3Design evolution: which classes change?
Using the pattern code in this topic, three change requests arrive: (i) send alerts on WhatsApp as well as SMS; (ii) accept payments through a second bank whose API differs from the first; (iii) offer a flat-rate EMI option for a short-term repair-loan scheme. For each, list the classes added and the classes modified.
EX 4Which pattern fits?
Name the GoF pattern for each need: (a) exactly one connection-pool manager for the whole application; (b) a simple single entry point hiding the allotment sub-system's many classes; (c) undo for edits made by a clerk; (d) one 'Generate report' routine whose steps are fixed but whose formatting step differs for PDF and Excel; (e) load scanned documents only when a clerk actually opens them; (f) the scheme hierarchy State → District → Scheme → Block → Unit, treated uniformly for totals.
Practice session
Work each problem on paper first, then check. Marking one solved earns 10 XP.0/5 solved
Q1
Write the coupling types from best to worst and the cohesion types from best to worst. Which coupling type does Rajib Mall's five-type list omit?
Q2
A class LoanManager computes EMIs, prints sanction letters as PDF, sends SMS, saves to the database, and contains a switch statement on schemeType that must be edited for every new scheme. Which SOLID principles does it violate, and how would you fix it?
Q3
Classify each GoF pattern as creational, structural or behavioural: Facade, Iterator, Builder, Proxy, Command, Composite, Prototype, Template Method.
Q4
Apply grammatical analysis to: 'A Board officer schedules an allotment draw for a scheme. The system randomly ranks eligible applications in each reservation category and allots units in rank order. Each allotted applicant receives an allotment letter.' List candidate classes, attributes and operations.
Q5
Choose an architectural pattern for each: (a) the nightly job that reads, validates, matches and posts bank files; (b) a dashboard showing the same arrears data as a table, a chart and a map; (c) a CASE toolset in which editors, checkers and generators share one model; (d) a system whose inner core must be protected by several security levels; (e) a database used by 14 district offices over the network.
Exam traps
Coupling should be LOW and cohesion HIGH. Options such as 'high coupling, high cohesion' or 'low cohesion, low coupling' are wrong.
Data coupling is the best (lowest) and content coupling the worst; functional cohesion is the best and coincidental the worst. Temporal cohesion ranks above logical.
Stamp vs data coupling: passing a whole record when only one field is needed is stamp coupling, even though it 'looks like' passing data.
Adapter changes an interface; Decorator keeps the interface and adds responsibilities; Proxy keeps the interface and controls access; Facade offers a new, simpler interface to a whole sub-system.
Strategy vs State: both delegate to interchangeable objects, but in Strategy the client chooses the algorithm, while in State the object switches its own state object as its state changes.
Design patterns are not code libraries, and they are not limited to the initial design — they are frequently introduced later through refactoring (PSC 2025).
Quiz — KPSC style
12 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.