CSC364 Software Engineering

Software EngineeringUnit 514 min read

Software Architecture & Design: Views, Patterns, Trade-offs & Real Systems

Unit 5 of Software Engineering covers architectural styles (layered, MVC, pipes/filters), design principles (SOLID, DRY), trade-off analysis (performance vs. cost), and real-world applications in Nepalese tech (eSewa, Ncell) and global systems (Google, WhatsApp). Learn how to model architectures, evaluate patterns, and

TAKEAWAYS:

  • Architectural views (logical, physical, process) let you design systems from different angles—use them to spot conflicts early.
  • Patterns like MVC and layered solve common problems (separation of concerns, scalability) but have trade-offs (e.g., MVC’s tight coupling).
  • COCOMO turns code size (KLOC) into effort estimates—critical for bidding projects (e.g., NTC’s billing system).
  • Design principles (e.g., SOLID) prevent technical debt; violate them, and your system becomes a "big ball of mud."
  • Real-world systems (eSewa’s microservices, WhatsApp’s event-driven design) show how theory maps to billion-user apps.
  • Trade-offs (e.g., consistency vs. availability in CAP theorem) force you to pick the right "wrong" answer for your context.

Core Concepts: What Is Software Architecture?

Software architecture is the high-level structure of a system—its components, their interactions, and the principles guiding its design. It answers:

  • What are the major parts? (e.g., database, UI, APIs)
  • How do they communicate? (e.g., REST calls, message queues)
  • Why did we choose this structure? (e.g., scalability, security)

Why it matters: Poor architecture leads to systems that are hard to maintain, slow to scale, or prone to crashes (e.g., early Facebook’s monolith vs. today’s microservices).


1. Architectural Views: Seeing the System Differently

Architectures are designed from multiple perspectives. The 4+1 View Model (Kruchten) defines:

mindmap
  root((Architectural Views))
    Logical View["Components & classes\n(e.g., UserService, OrderRepository)"]
    Process View["Concurrency & threads\n(e.g., Pathao’s rider dispatch threads)"]
    Development View["Modules & build structure\n(e.g., Daraz’s frontend/backend repos)"]
    Physical View["Nodes & deployment\n(e.g., Ncell’s CDN servers in Kathmandu/Pokhara)"]
    +1 Scenario["Use cases driving design\n(e.g., ‘Place order in 3 seconds’)"]

Example: For eSewa’s payment system, the logical view might include UserAuth, TransactionProcessor, and BankGateway components, while the physical view shows these deployed across Kathmandu’s data centers and banks’ servers.


2. Architectural Styles: Patterns for Common Problems

Different styles solve different problems. Here are the top 3 you’ll see in exams:

Presentation → Business → DataLayered (N-Tier)Model-View-ControllerMVCData → Transform → OutputPipe & FilterPublish-SubscribeEvent-DrivenArchitectural Styles
Comparison of key architectural styles

A. Layered (N-Tier) Architecture

How it works:


  • Layers: UI → Application → Data (e.g., Daraz’s website → order processing → database).
  • Rules:
    • Layers only communicate with adjacent layers (e.g., UI calls Application, not the database directly).
    • Changes in one layer (e.g., switching databases) shouldn’t break others.

Pros/Cons:

Pros Cons When to Use
Easy to understand Performance bottlenecks (e.g., UI waits for DB) Small to medium apps (e.g., bank ATMs)
Reusable layers (e.g., auth logic) Hard to scale horizontally Internal tools, CRUD apps

Worked Example: NTC’s Billing System

  • Layers:
    1. Presentation: Web/mobile UI for customers to check bills.
    2. Application: Business logic (e.g., "Apply 10% discount if paid early").
    3. Data: SQL database storing customer records.
  • Trade-off: Adding a caching layer (e.g., Redis) between Application and Data could speed up bill lookups but adds complexity.

B. Model-View-Controller (MVC)

How it works:

ModelViewController
MVC interaction flow (user → View → Controller → Model → View)
  • Model: Data and business logic (e.g., Order class with calculateTax()).
  • View: UI (e.g., Daraz’s product page).
  • Controller: Mediates between Model and View (e.g., handles HTTP requests).

Pros/Cons:

Pros Cons When to Use
Separates concerns (e.g., UI changes don’t break logic) Tight coupling between Controller and Model Web apps (e.g., eSewa’s dashboard)
Easy to test (mock Models) Overkill for simple apps Single-page apps (React/Angular)

Real-World Tie: WhatsApp Web

  • Model: Your chat messages stored locally + synced with servers.
  • View: The UI showing messages, emojis, and status.
  • Controller: Handles keyboard input, scroll events, and API calls to WhatsApp’s servers.

C. Pipe and Filter

How it works:

flowchart TD
  A["Input Data: Raw Log Files"] -->|"Parse JSON"| B["Filter 1"]
  B -->|"Stream"| C["Pipe"]
  C -->|"Validate"| D["Filter 2"]
  D -->|"Stream"| E["Pipe"]
  E -->|"Aggregate"| F["Filter 3"]
  F -->|"Output"| G["Dashboard"]
Pipe-and-Filter architecture with data transformation stages
  • Filters: Independent processes that transform data (e.g., ParseLog, CalculateMetrics).
  • Pipes: Data streams between filters (e.g., Unix pipes |).

Pros/Cons:

Pros Cons When to Use
Highly reusable filters Hard to debug (data flows invisibly) Data processing (e.g., Google Analytics)
Parallelizable (e.g., split logs by server) Overhead for simple tasks ETL pipelines (Extract-Transform-Load)

Real-World Tie: YouTube’s Video Processing

  1. Filter 1: Extract audio from raw video.
  2. Pipe: Stream audio to encoding server.
  3. Filter 2: Encode audio to AAC format.
  4. Pipe: Merge encoded audio back with video.
  5. Filter 3: Generate thumbnails.

3. Design Principles: Rules of Thumb

Violate these, and your system becomes a spaghetti mess. Key principles:

A. SOLID Principles

Principle What It Means Example Violation → Fix
Single Responsibility A class/module does one thing. UserManager handles auth, profiles, and emails → Split into AuthService, ProfileService.
Open/Closed Open for extension, closed for modification. Hardcoded discount logic → Use strategy pattern (e.g., DiscountStrategy interface).
Liskov Substitution Subclasses must be substitutable. Square extending Rectangle breaks area() → Use composition instead.
Interface Segregation Small, role-specific interfaces. Monolithic IDatabase interface → Split into IReadDB, IWriteDB.
Dependency Inversion Depend on abstractions, not concretions. Order directly uses MySQLConnection → Inject IDatabase interface.

B. DRY (Don’t Repeat Yourself)

  • Problem: Duplicate code leads to bugs (e.g., changing a tax calculation in two places).
  • Solution: Abstract common logic into functions/classes.
  • Example: NEPSE’s Trading System
    • Bad: Copy-pasting calculateTax() in every script.
    • Good: One TaxCalculator class used by all modules.

4. Trade-offs: There’s No Free Lunch

Every design decision involves trade-offs. Key examples:

ConflictConflictConflictConsistencyAvailabilityPartition Tolerance
CAP Theorem trade-off triangle (pick 2)

A. CAP Theorem: Consistency, Availability, Partition Tolerance

Choice Consistency Availability Partition Tolerance Example
CP ✅ High ❌ Low ✅ Yes Banks (transactions must be consistent, even if a server fails).
AP ❌ Low ✅ High ✅ Yes WhatsApp (messages may briefly show as "delivered" before syncing).
CA ✅ High ✅ High ❌ No Single-server apps (e.g., old eSewa).

Real-World Tie: Pathao’s Rider App

  • Trade-off: During traffic jams, Pathao prioritizes availability (showing nearby riders) over consistency (real-time rider locations may lag).

B. Performance vs. Cost

Optimization Performance Gain Cost Example
Add caching (Redis) Faster reads Higher server costs Daraz’s product catalog
Use CDN Lower latency CDN fees Ncell’s mobile app assets
Database indexing Faster queries Slower writes eSewa’s transaction logs

5. COCOMO Model: Estimating Effort

The Constructive Cost Model (COCOMO) estimates effort (person-months) and time based on KLOC (thousands of lines of code).

Formulas:

  • Organic Mode (small team, familiar tech): Effort (PM) = 2.4 × (KLOC)^1.05 Time (months) = 2.5 × (Effort)^0.38
  • Embedded Mode (complex, real-time systems): Effort (PM) = 3.6 × (KLOC)^1.20 Time (months) = 2.5 × (Effort)^0.32

Worked Example: NTC’s New Billing System (320 KLOC)

  1. Organic Mode:
    • Effort = 2.4 × (320)^1.05 ≈ 2.4 × 339.5 ≈ 815 person-months.
    • Time = 2.5 × (815)^0.38 ≈ 2.5 × 6.1 ≈ 15.3 months.
  2. Embedded Mode:
    • Effort = 3.6 × (320)^1.20 ≈ 3.6 × 423.6 ≈ 1,525 person-months.
    • Time = 2.5 × (1,525)^0.32 ≈ 2.5 × 7.2 ≈ 18 months.

Why it matters: Helps NTC decide whether to outsource (cheaper labor) or hire locally.


6. Risk Management in Architecture

Architectural decisions introduce risks. Example risks and mitigations:

Risk Impact Mitigation Strategy
Monolithic design Hard to scale Start with microservices (e.g., WhatsApp).
Tight coupling Changes break other modules Use interfaces (e.g., SOLID’s D principle).
Single point of failure System crashes if one node dies Redundancy (e.g., Ncell’s backup servers).
Vendor lock-in Stuck with a cloud provider Multi-cloud design (e.g., Google + AWS).

Real-World Tie: Khalti’s Payment Gateway

  • Risk: Relying solely on Nepal’s banking infrastructure (slow updates).
  • Mitigation: Built a fallback system to handle bank outages during Dashain.

In the Real World

  1. eSewa’s Microservices Architecture

    • Idea Used: Layered + Service-Oriented Architecture (SOA)
    • How: eSewa breaks its system into services:
      • AuthService (handles login via bank credentials).
      • PaymentService (processes transactions).
      • NotificationService (sends SMS/email alerts).
    • Why: Each service can scale independently (e.g., PaymentService gets more servers during Dashain).
  2. Pathao’s Event-Driven Design

    • Idea Used: Pipe and Filter + Event Sourcing
    • How: When a rider accepts an order:
      1. Event: OrderAccepted is published.
      2. Filters:
        • Update rider’s currentOrder in DB.
        • Send notification to customer.
        • Log event for analytics.
    • Why: Decouples components (e.g., UI can update without waiting for DB).
  3. Ncell’s CDN for Mobile Apps

    • Idea Used: Trade-off: Cost vs. Latency
    • How: Ncell uses Cloudflare’s CDN to cache app assets (images, JS) closer to users.
    • Result: Faster loads in Pokhara/Kathmandu, but costs $X/month.
    • Alternative: Self-hosted servers (cheaper but slower for remote users).

Exam Tip: How to Score Full Marks

  1. Diagrams Are Mandatory

    • For MVC/layered architectures, draw the components and arrows. Label every box and connection.
    • Example: For MVC, show Model ←→ Controller ←→ View with arrows for data flow.
  2. Compare Styles in Tables

    • Exams often ask: "When would you use layered vs. MVC?"
    • Do this:
      Style Best For Avoid When
      Layered CRUD apps (e.g., ATMs) High-performance needs
      MVC Web apps (e.g., eSewa) Real-time systems (use event-driven instead)
  3. COCOMO Calculations

    • Show your steps: Write down the formula, plug in KLOC, and box your final answer.
    • Units matter: Always label effort as "person-months" and time as "months."
  4. Real-World Examples

    • Tie every concept to Nepalese tech (eSewa, Ncell, Daraz) or global apps (WhatsApp, Google).
    • Example answer for "Explain layered architecture":

      "Layered architecture is used in NTC’s billing system, where the UI layer (web portal) communicates with the business logic layer (discount calculations) via REST APIs, which in turn queries the data layer (MySQL database). This separation allows NTC to update the UI (e.g., add mobile support) without changing the backend logic."

  5. Trade-offs Are Key

    • Questions like "Why didn’t WhatsApp use a layered architecture?" expect:

      "WhatsApp prioritizes availability and scalability over strict layer separation. Its event-driven architecture (e.g., message queues) allows horizontal scaling, while layered design would create bottlenecks between UI and database layers during peak usage (e.g., 2 AM in Kathmandu)."


Common Pitfalls to Avoid

  • Vague answers: Don’t say "MVC separates concerns" without naming what is separated (e.g., "UI logic from business rules").
  • Ignoring trade-offs: Always mention one trade-off for every architecture (e.g., "Layered is simple but can’t scale like microservices").
  • Assuming "best" architecture: There’s no one-size-fits-all—always justify your choice (e.g., "For a bank, CP (consistency) is more important than AP (availability).").

Based on the TU BSc CSIT syllabus for Software Engineering (CSC364), unit 5.

Discussion

Loading…