Topics 27 to 39 • Modularity, Cohesion, Coupling, SOLID Principles, Use Case, Class, Sequence & Activity Diagrams
Software Design bridges the gap between the requirements domain and the implementation domain. It defines the internal organization of software components, interfaces, and data structures.
Cohesion measures the degree of functional relatedness among elements inside a single module. High cohesion is the hallmark of superior software design!
| Cohesion Level | Quality Rating | Description | Concrete Code Example |
|---|---|---|---|
| 1. Coincidental | Worst (0/10) | Elements grouped purely at random with zero logical relationship. | `Utilities.java` containing `calculateTax()`, `printString()`, `sortArray()`. |
| 2. Logical | Poor (2/10) | Elements perform logically similar functions selected via a control flag. | `handleInput(int flag)` where flag 1=Mouse, flag 2=Keyboard, flag 3=Network. |
| 3. Temporal | Fair (4/10) | Elements executed together during the same timeframe. | `systemStartup()` initializing DB connections, loading config files, and clearing cache. |
| 4. Procedural | Moderate (5/10) | Elements executed in a specific sequence to accomplish a broader task. | `processOrder()`: `checkStock()` $\rightarrow$ `deductBalance()` $\rightarrow$ `printReceipt()`. |
| 5. Communicational | Good (7/10) | Elements operate upon the exact same shared input dataset. | `analyzeStudentRecords()`: `computeGPA(student)` and `generateTranscript(student)`. |
| 6. Sequential | Very Good (8.5/10) | Output of one element serves as the direct input to the next element (pipeline). | `parseXML(file)` $\rightarrow$ `validateSchema(xml)` $\rightarrow$ `insertToDB(records)`. |
| 7. Functional | Best (10/10) | Every element contributes strictly to executing exactly one well-defined mathematical or business task. | `Math.sin(angle)`, `calculateCompoundInterest(P, r, n, t)`. |
Coupling measures the degree of interdependence between separate software modules. Low coupling minimizes ripple effects during system maintenance!
| Coupling Level | Quality Rating | Description | Concrete Architecture Example |
|---|---|---|---|
| 1. Content | Worst (High) | One module directly accesses and modifies internal code or private data of another module. | Module A branches into the middle of Module B via `goto` or directly mutates B's private pointers. |
| 2. Common | Very Poor | Multiple modules read and write to shared global variables or shared memory pools. | Modules A, B, and C all mutating global variable `int g_system_state;`. |
| 3. Control | Poor | One module passes a control flag that dictates the internal execution path of another module. | `calculatePayroll(employee, boolean isExecutive)`. |
| 4. Stamp (Data-Structured) | Fair / Good | Modules pass a complete composite data structure when only a few fields are needed. | Passing complete `Customer` object (30 fields) to a function that only needs `customer.zipCode`. |
| 5. Data | Very Good | Modules communicate strictly by passing atomic primitive parameters through interfaces. | `computeTax(double salary, double taxRate)`. |
| 6. Message / No Coupling | Best (Lowest) | Modules communicate asynchronously via message queues with zero shared state. | Microservices communicating via RabbitMQ JSON events. |
| Principle | Core Definition | Violation vs. Clean Architectural Solution |
|---|---|---|
| S — Single Responsibility (SRP) | A class should have one, and only one, reason to change. | Violation: `User` class handling business logic + database saving + PDF email formatting. Solution: Split into `User`, `UserRepository`, and `UserInvoicePdfService`. |
| O — Open/Closed (OCP) | Software entities should be open for extension, but closed for modification. | Violation: Using huge `switch(shapeType)` statements to compute areas. Solution: Define abstract `Shape` interface with polymorphic `calculateArea()` implementations (`Circle`, `Rectangle`). |
| L — Liskov Substitution (LSP) | Subtypes must be substitutable for their base types without altering correctness. | Violation: `Square` inheriting from `Rectangle` where mutating width unexpectedly changes height. Solution: Extract common `Shape` interface; do not force square-rectangle inheritance. |
| I — Interface Segregation (ISP) | Clients should not be forced to depend upon interfaces they do not use. | Violation: Massive `IMachine` with `print()`, `scan()`, `fax()`, `staple()`. Solution: Segregate into `IPrinter`, `IScanner`, `IFax`. |
| D — Dependency Inversion (DIP) | High-level modules should not depend on low-level modules; both should depend on abstractions. | Violation: `OrderService` directly instantiating `MySQLDatabase db = new MySQLDatabase();`. Solution: Inject interface `IDatabase` via Dependency Injection. |
The Unified Modeling Language (UML) is the standard graphical language for specifying, visualizing, constructing, and documenting software system artifacts.
| Dimension | Aggregation (Shared Association) | Composition (Composite Association) |
|---|---|---|
| UML Symbol | Hollow / White Diamond ($\diamond$) at whole end. | Filled / Black Solid Diamond ($\blacklozenge$) at whole end. |
| Ownership | Weak ownership ("Has-A"). Parts can belong to multiple wholes. | Strong, exclusive ownership ("Part-Of"). Child belongs to exactly one parent. |
| Lifecycle Binding | Independent. If whole is destroyed, parts continue to exist. | Coincident. If whole is destroyed, all child components are automatically deleted. |
| Real-World Example | `University` $\diamond\text{---}$ `Professor` (If university closes, professor exists). | `House` $\blacklozenge\text{---}$ `Room` (If house is demolished, rooms cease to exist). |
| Architectural Style | Structural Organization | Key Strengths | Limitations |
|---|---|---|---|
| Layered (N-Tier) | Hierarchical layers (Presentation $\rightarrow$ Business Logic $\rightarrow$ Data Access $\rightarrow$ Database). | Clear separation of concerns; easy to test layers in isolation. | Performance overhead due to cascading calls through every intermediate layer. |
| Pipe and Filter | Sequential stream where filters process data and pass streams through pipes (e.g., Unix CLI, ETL). | High reusability; filters can execute concurrently in parallel threads. | Difficult to handle interactive event-driven UI workflows. |
| Event-Driven (Pub-Sub) | Decoupled producers publish event messages to an event bus (Kafka); consumers subscribe. | Massive scalability; extreme decoupling between producers and consumers. | Eventual consistency challenges; difficult to trace distributed execution flow. |
| Microservices | Suite of independently deployable small services structured around business domains. | Independent horizontal scaling; polyglot technology stacks. | Complex distributed networking, network latency, distributed transaction rollbacks (Saga pattern). |
| Pattern Family | Classic Design Pattern | Architectural Purpose & Implementation Mechanism |
|---|---|---|
| Creational | Singleton Pattern | Guarantees a class has strictly one global instance with private constructor and synchronized `getInstance()`. |
| Creational | Factory Method | Defines an interface for creating an object, but lets subclasses decide which concrete class to instantiate. |
| Structural | Adapter Pattern | Converts the interface of a class into another interface clients expect, bridging incompatible interfaces. |
| Structural | Facade Pattern | Provides a unified, simplified high-level interface to a complex subsystem of dozens of internal classes. |
| Behavioral | Observer Pattern | Defines a one-to-many dependency where state changes in a Subject automatically notify all registered Observers. |
| Behavioral | Strategy Pattern | Encapsulates interchangeable algorithmic families inside separate classes, switching algorithms dynamically at runtime. |
OCL is a formal declarative specification language used within UML class diagrams to specify precise mathematical constraints and business rules without implementation code:
-- Invariant: Bank Account balance cannot drop below overdraft limit
context BankAccount
inv: self.balance >= -self.overdraftLimit
-- Pre-condition and Post-condition on withdrawal operation
context BankAccount::withdraw(amount: Real): Boolean
pre: amount > 0 and (self.balance - amount >= -self.overdraftLimit)
post: self.balance = self.balance@pre - amount and result = true
Problem: A monolithic billing class uses complex nested conditionals: `if (type == "CREDIT") chargeCredit(); else if (type == "PAYPAL") chargePayPal(); ...` (Violates Open/Closed Principle!).
Refactoring Solution:
| Family | Pattern Name | Intent & Structural Mechanism |
|---|---|---|
| Creational | Builder Pattern | Separates the construction of a complex object from its representation, allowing the same construction process to create different representations. |
| Creational | Prototype Pattern | Specifies the kind of objects to create using a prototypical instance, creating new objects by cloning this prototype. |
| Structural | Decorator Pattern | Attaches additional responsibilities to an object dynamically at runtime, providing a flexible alternative to subclassing. |
| Structural | Proxy Pattern | Provides a surrogate or placeholder for another object to control access to it (e.g., Virtual Proxy, Remote Proxy, Protection Proxy). |
| Behavioral | Command Pattern | Encapsulates a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations. |
| Behavioral | State Pattern | Allows an object to alter its behavior when its internal state changes. The object will appear to change its class. |
| Behavioral | Template Method | Defines the skeleton of an algorithm in an operation, deferring some steps to subclasses without changing algorithm structure. |
Rather than creating $2^n$ subclasses (`EspressoWithCaramelAndMilk`), wrap base `Coffee` with `CaramelDecorator` and `MilkDecorator`, dynamically chaining `getCost()`: $5 + 2 + 1 = \$8$!
• Lack of Cohesion in Methods (LCOM - Chidamber & Kemerer): Let $P$ be method pairs with disjoint attribute sets, $Q$ be method pairs sharing attributes. $\text{LCOM} = \max(0, |P| - |Q|)$. High LCOM $\implies$ Poor cohesion (class should be split!).
• Coupling Between Objects (CBO): Count of external classes to which a class is coupled. High CBO $\implies$ High ripple effect vulnerability during refactoring!
Subject `StockTicker` maintains `List
Model an ATM Card Reader with composite state `Card Processing` containing substates `PIN Verification` and `Account Selection` with shallow history node ($H$) restoring previous active substate upon momentary power fluctuation!
• Component Diagram: Models physical software modules (JARs, DLLs, Docker images) with `<
• Deployment Diagram: Models physical hardware compute nodes (Web Server, Database Server) and execution environments connected via communication paths (`TCP/IP`, `gRPC`).
// Refactored Clean Architecture adhering strictly to Open/Closed Principle
public interface Shape { double calculateArea(); }
public class Circle implements Shape {
private double radius;
public Circle(double radius) { this.radius = radius; }
public double calculateArea() { return Math.PI * radius * radius; }
}
public class AreaCalculator {
public double totalArea(List shapes) {
return shapes.stream().mapToDouble(Shape::calculateArea).sum();
}
}
Verification: Adding a new `Triangle` shape requires zero edits to `AreaCalculator`, achieving $100\%$ modification immunity!
In a Graphical Windowing system: Rather than declaring 32 subclasses (`BorderedScrollableDarkWindow`), dynamically attach `BorderDecorator`, `ScrollDecorator`, and `ThemeDecorator` wrapping the base `Window` interface!
• Factory Method: Uses inheritance and relies on a derived class to instantiate a single product object (`createButton()`).
• Abstract Factory: Uses object composition to create entire families of related or dependent objects without specifying their concrete classes (`GUIFactory` creates `Button`, `Checkbox`, `Scrollbar` together)!
A method $M$ of object $O$ should only call methods of: (1) $O$ itself, (2) $M$'s parameters, (3) objects created within $M$, (4) $O$'s direct member objects. Prohibits train wrecks: `a.getB().getC().getD().doSomething()` $\implies$ Refactor to `a.doSomething()`!
public class DatabaseConnectionPool {
private static volatile DatabaseConnectionPool instance;
private DatabaseConnectionPool() { /* Initialize pool */ }
public static DatabaseConnectionPool getInstance() {
if (instance == null) {
synchronized (DatabaseConnectionPool.class) {
if (instance == null) {
instance = new DatabaseConnectionPool();
}
}
}
return instance;
}
}
Client expects `ModernPayment` interface (`pay(amount)`). Legacy gateway uses `OldGateway` (`makeTransaction(cents, currency)`). `PaymentAdapter` implements `ModernPayment`, delegating and converting dollars to cents internally!
In a home theater system: `HomeTheaterFacade` exposes a single simple `watchMovie()` method that coordinates `Projector.on()`, `SoundSystem.setVolume()`, `DvdPlayer.play()`, and `Lights.dim()`, shielding external callers from 15 separate low-level interfaces!
Each user action is an instance of `Command` with `execute()` and `undo()` methods stored on a history stack, enabling infinite multi-level undo/redo operations!
• Abstract Factory: Focuses on creating families of related objects all at once.
• Builder: Focuses on constructing a complex composite object step-by-step through a fluent API (`User.builder().name("Alice").age(30).build()`)!
(1) Virtual Proxy (defers loading huge images/DB records until needed), (2) Protection Proxy (checks user authorization permissions before invoking target object), (3) Remote Proxy (handles network serialization via gRPC/RMI)!
When subjects hold strong references to observers, forgotten unregistered observers cause memory leaks (Lapsed Listener Problem). Fix by storing observers via `WeakReference
`FileSystemComponent` is implemented by leaf `File` and composite `Directory` containing `List
Decouples the sender of a request from its receivers by giving multiple handler objects (`AuthHandler` $\rightarrow$ `RateLimitHandler` $\rightarrow$ `ValidationHandler`) a chance to handle the request!
Prevents an $O(n^2)$ web of direct object references by routing all dialog component interactions (`Button`, `TextBox`, `ListBox`) through a central `DialogMediator`!
Separates algorithm operations (`TypeCheckerVisitor`, `CodeGeneratorVisitor`) from complex heterogeneous object node hierarchies (`BinaryExpr`, `AssignStmt`), letting you add new compiler passes without modifying node classes!
• God Object (Blob): Single monolithic class monopolizing all system logic $\implies$ Refactor into cohesive services.
• Spaghetti Code: Unstructured control flow with high coupling $\implies$ Refactor to layered architecture.
• Lava Flow: Dead legacy code nobody dares touch $\implies$ Eliminate using test-driven refactoring!
Decomposes complex enterprise domains into distinct Bounded Contexts (`BillingContext`, `ShippingContext`), ensuring terms have unambiguous definitions within their domain boundaries!
Decouples an abstraction (`Window`) from its platform-specific implementation (`WinWindowImpl`, `MacWindowImpl`, `LinuxWindowImpl`), allowing both hierarchies to vary independently!
Captures and externalizes an object's internal state without violating encapsulation, allowing the state to be restored later (`GameStateMemento`)!
• Fail-Fast Iterator (Java `ArrayList`): Throws `ConcurrentModificationException` immediately if collection is modified structurally during traversal.
• Fail-Safe / Snapshot Iterator (`CopyOnWriteArrayList`): Operates on a cloned snapshot of the array, permitting concurrent multi-threaded modifications with zero locking overhead!
In a text editor containing 1,000,000 characters: Rather than creating 1,000,000 separate `Character` objects, share 26 intrinsic font glyph objects (`GlyphFactory`) and pass coordinates externally, slashing RAM consumption from 80MB to 200KB!
Encapsulates distinct state-specific behaviors inside polymorphic subclasses (`DraftState`, `ModerationState`, `PublishedState`), eliminating massive 500-line nested `switch-case` statements in Document publishing workflows!
• Event Sourcing: Persists state mutations as an append-only log of immutable domain events (`OrderPlaced`, `PaymentReceived`).
• CQRS: Segregates Command (write) models from Query (read) models, scaling read performance independently by $100\times$!
Using distributed Kafka change data capture (CDC) streams to asynchronously replicate write model commits to Elasticsearch read indexes with sub-second lag!
Context `NavigationEngine` swaps `DijkstraShortestPath`, `AStarTrafficAware`, and `EcoFriendlyRoute` strategies at runtime based on real-time GPS telemetry!
Abstract class `DataETLPipeline` defines `process()` executing `extract()`, `transform()`, and `load()`, while letting subclasses override `extract()` for SQL or NoSQL sources!
Modeling modular boundaries with `<
• 2PC: Synchronous blocking distributed transaction locking databases across network boundaries; fails under network partitions.
• Saga Pattern: Asynchronous choreography/orchestration executing local transactions with compensating rollback actions (`cancelOrder()`), guaranteeing eventual consistency without blocking locks!
Polymorphically visiting syntax nodes (`VariableDecl`, `FunctionCall`, `BinaryOp`) to infer hindley-milner types with zero AST class pollution!
Consolidates routing, SSL termination, rate limiting, and JWT authentication token validation into a single reverse-proxy entrypoint (Kong / Spring Cloud Gateway), preventing client coupling to 50 downstream microservices!
• WMC (Weighted Methods per Class): Measures class complexity.
• DIT (Depth of Inheritance Tree): Deep trees ($> 5$) increase fragility.
• NOC (Number of Children): High NOC indicates high reuse but severe change ripple risk!