Chapter 21 of 32

Software Design Principles

Requirements tell us what the system must do. The SRS from the Software Requirements Specification (SRS) chapter is the contract. Design is the step where we decide how the system will do it: which parts it has, what each part is responsible for, and how the parts talk to each other.

Two programs can satisfy the same SRS and still be very different to live with. One is easy to change, test and extend. The other breaks in three places every time you touch it. The difference is almost always in the design. This chapter covers the principles that experienced engineers use to tell a good design from a bad one.

Software design is the process of transforming requirements into a blueprint of the solution: a description of the system's components, their responsibilities, their interfaces and their relationships, detailed enough to guide construction.


Why Design Deserves Its Own Phase

A building analogy helps. You can build a small shed without drawings. You cannot build a ten-floor hostel that way: the plumbing, wiring and load-bearing walls must be planned before the first brick, because moving them later is very expensive.

Software is the same. In the Software Characteristics & Software Crisis chapter we saw that software does not wear out, but it does deteriorate as changes pile up. A good design slows that deterioration. Concretely, design work pays off because:

  • Fixing a design flaw is cheaper before coding. Changing a box on a diagram costs minutes; changing 40 files that depend on a bad decision costs weeks.

  • It lets a team work in parallel. Once interfaces are agreed, different developers can build different modules at the same time.

  • It makes the system understandable. New team members learn the structure from the design instead of reading every line.

  • It is where quality attributes are decided. Performance, security, maintainability and scalability are mostly fixed by structure, not by clever lines of code.

Levels of design

Design usually happens at two levels:

LevelAlso calledDecidesExample output
Architectural designHigh-level design (HLD)Major subsystems, how they communicate, technology choices, deployment"Web front end + REST API + PostgreSQL; payments via an external gateway"
Detailed designLow-level design (LLD), component designClasses/functions inside each module, data structures, algorithms, interfacesClass diagram of the Order module; pseudocode of the fee calculation

Some textbooks (Pressman) also list data design and interface design as separate design elements. The principles below apply at every level.


Characteristics of a Good Design

Before the principles, let us agree on the goal. A good design is:

  • Correct and complete: it implements every requirement in the SRS.

  • Understandable: a competent developer can read it and see how the system works.

  • Maintainable: a change in one requirement affects as few parts as possible.

  • Efficient: it does not waste time or memory without reason.

  • Testable: parts can be tested in isolation.

Notice that "understandable" and "maintainable" appear before "efficient". Most software spends far more of its life being maintained than being written, so a slightly slower but clear design usually beats a fast but tangled one.


The Fundamental Design Concepts

These concepts come from classic texts (Pressman, Sommerville) and are the ones university exams ask about most.

1. Abstraction

Abstraction means focusing on the essential properties of something while hiding the details that are not relevant at the current level.

When you call sort(list), you think "it sorts", not "it does a merge sort with these index variables". There are three common kinds:

  • Procedural abstraction: a named sequence of steps with a clear purpose, such as calculateFee() or "open the door".

  • Data abstraction: a named collection of data that describes an object, such as Student with name, roll number and branch, without saying how it is stored.

  • Control abstraction: a control mechanism used without exposing its internals, such as a semaphore or an event loop.

2. Stepwise refinement

Proposed by Niklaus Wirth (1971). You start with a high-level statement of the function and refine it step by step, adding detail at each step, until it is close enough to code.

Level 0:  Generate result card for a student

Level 1:  read marks of all subjects
          compute total and percentage
          decide grade
          print result card

Level 2 (refining "decide grade"):
          if percentage ≥ 75 → "Distinction"
          else if percentage ≥ 60 → "First Class"
          else if percentage ≥ 40 → "Pass"
          else → "Fail"

Abstraction and refinement are two sides of the same coin: abstraction hides detail, refinement reveals it gradually.

3. Modularity

Dividing the software into separately named, addressable components called modules that together satisfy the requirements. Modularity is so central that the next chapter, Modularity, Coupling & Cohesion, is devoted to it, including how to measure whether a split is good. For now, remember the key idea: a problem split into well-chosen parts is easier to solve than the whole problem at once, but splitting into too many tiny parts adds interface overhead.

4. Information hiding

Introduced by David Parnas (1972). Each module should hide a design decision that is likely to change (a data structure, a file format, an algorithm), and expose only a stable interface.

Information hiding: modules should be specified and designed so that the information (data and algorithms) inside one module is inaccessible to other modules that have no need for it.

Example: a Timetable module stores classes internally in a list today. Other modules only call getClasses(day). Tomorrow you switch to a dictionary keyed by day for speed. No other module changes, because no one ever saw the list.

Information hiding is the idea; encapsulation (private fields + public methods in a class) is one common language mechanism for achieving it.

5. Separation of concerns

A concern is a feature or behaviour that is part of the requirements, such as "validate input", "store data" or "show the page". Separation of concerns says each concern should be handled in its own part of the design, so it can be understood and changed on its own.

The classic example is a layered web application:

+-------------------------+
|  Presentation layer     |  HTML pages, forms, API responses
+-------------------------+
|  Business logic layer   |  fee rules, eligibility checks
+-------------------------+
|  Data access layer      |  SQL queries, ORM
+-------------------------+
          |
     [ Database ]

Changing the page colour never touches fee rules; changing from MySQL to PostgreSQL only touches the bottom layer.

6. Functional independence

A module is functionally independent when it does one clear job and has little interaction with other modules. It is measured by two qualities: cohesion (how focused a module is, aim for high) and coupling (how dependent modules are on one another, aim for low). Both are explained fully in the next chapter.

7. Refactoring

Improving the internal structure of code without changing its external behaviour (Martin Fowler's definition). Examples: renaming a confusing variable, extracting a long function into smaller ones, removing duplicate code. Refactoring is how a design stays good after many changes, and it is safe only when good automated tests exist to confirm that behaviour has not changed (testing is covered later in this tutorial).

8. Patterns

A design pattern is a named, proven solution to a recurring design problem in a given context. The 1994 "Gang of Four" book catalogued 23 of them (Singleton, Observer, Strategy, Factory Method, and so on). Patterns give teams a shared vocabulary: saying "use a Strategy here" communicates a whole design in three words.


Top-Down vs Bottom-Up Design

AspectTop-downBottom-up
Starting pointThe whole system, decomposed into subsystemsSmall, basic components, combined into bigger ones
Based onStepwise refinementReuse of existing building blocks
Best whenThe problem is new and well specifiedGood libraries or components already exist
RiskLow-level problems (performance, feasibility) found lateParts may not fit the overall goal

In practice, most teams use a hybrid: top-down for the architecture, bottom-up for reusing frameworks and libraries.


Function-Oriented vs Object-Oriented Design

AspectFunction-oriented design (FOD)Object-oriented design (OOD)
Basic unitFunction / procedureObject (data + behaviour)
System viewSet of functions transforming dataSet of interacting objects
StateOften shared/global dataKept inside objects (encapsulated)
DecompositionBy function, top-downBy real-world or domain entities
Typical notationData Flow Diagrams, structure chartsUML class, sequence, state diagrams
Examples of methodsStructured Analysis / Structured Design (SA/SD)Booch, OMT, Rational Unified Process with UML

Later in this tutorial, the UML Diagrams chapter covers the OOD notation and the Data Flow Diagrams chapter covers the main FOD notation.


Modern Principles: SOLID

For object-oriented code, the most widely used set of principles is SOLID, a name popularised by Robert C. Martin. Interviewers ask about these constantly.

LetterPrincipleOne-line meaning
SSingle Responsibility PrincipleA class should have only one reason to change.
OOpen/Closed PrincipleOpen for extension, closed for modification.
LLiskov Substitution PrincipleObjects of a subtype must be usable wherever the base type is expected, without breaking correctness.
IInterface Segregation PrincipleClients should not be forced to depend on methods they do not use.
DDependency Inversion PrincipleHigh-level modules should depend on abstractions, not on concrete low-level modules.

S: Single Responsibility

A ReportCard class that computes grades, formats a PDF and emails parents has three reasons to change: grading rules, PDF layout, mail server. Split it into GradeCalculator, ReportFormatter and Mailer. Now a new PDF layout cannot break grade calculation.

O: Open/Closed (with runnable code)

Suppose checkout code has an if/elif chain for every discount type. Every new festival offer means editing (and re-testing) checkout. Instead, define an abstraction and add new classes:

from abc import ABC, abstractmethod

class Discount(ABC):
    @abstractmethod
    def apply(self, amount: float) -> float: ...

class NoDiscount(Discount):
    def apply(self, amount): return amount

class StudentDiscount(Discount):
    def apply(self, amount): return amount * 0.90      # 10% off

class FestivalDiscount(Discount):
    def apply(self, amount): return max(amount - 200, 0)  # flat Rs 200 off

def checkout(amount: float, discount: Discount) -> float:
    # checkout never changes when a new discount type is added
    return round(discount.apply(amount), 2)

for d in [NoDiscount(), StudentDiscount(), FestivalDiscount()]:
    print(f"{type(d).__name__:<17} -> Rs {checkout(1500, d)}")

Output:

NoDiscount        -> Rs 1500
StudentDiscount   -> Rs 1350.0
FestivalDiscount  -> Rs 1300

Adding a "Diwali 15% off" offer means writing one new class. checkout is closed for modification but the system is open for extension. (This is the Strategy pattern.)

L: Liskov Substitution

The textbook violation: Square inherits from Rectangle. Code that does r.setWidth(5); r.setHeight(4) and expects area 20 gets 16 when r is a square, because setting the height also changes the width. Mathematically a square "is a" rectangle, but behaviourally the subclass breaks the parent's promise. The fix is to not use inheritance here (for example, make both implement a common Shape with area()).

I: Interface Segregation

A single Machine interface with print(), scan() and fax() forces a simple printer to implement scan() and fax() with "not supported" errors. Split it into Printer, Scanner and Fax; a multifunction device implements all three.

D: Dependency Inversion (with runnable code)

A fee-reminder service should not create an email client inside itself. It should depend on "something that can send a message", and receive the concrete sender from outside (dependency injection):

class EmailSender:
    def send(self, to, msg): print(f"[email to {to}] {msg}")

class SmsSender:
    def send(self, to, msg): print(f"[sms to {to}] {msg}")

class FakeSender:                      # used in tests
    def __init__(self): self.sent = []
    def send(self, to, msg): self.sent.append((to, msg))

class FeeReminder:
    def __init__(self, sender):        # dependency is injected
        self.sender = sender
    def remind(self, student, due):
        self.sender.send(student, f"Fee of Rs {due} is due on 10th.")

FeeReminder(EmailSender()).remind("aman@college.edu", 45000)
FeeReminder(SmsSender()).remind("+91-98xxxxxx10", 45000)
fake = FakeSender()
FeeReminder(fake).remind("test-student", 100)
print("captured:", fake.sent)

Output:

[email to aman@college.edu] Fee of Rs 45000 is due on 10th.
[sms to +91-98xxxxxx10] Fee of Rs 45000 is due on 10th.
captured: [('test-student', 'Fee of Rs 100 is due on 10th.')]

Notice the bonus: because the dependency is swappable, a test can pass a FakeSender and check what would have been sent, without sending real messages. Good design and testability go together.


Other Everyday Principles

PrincipleMeaningTypical violation
DRY (Don't Repeat Yourself)Every piece of knowledge should have one authoritative place in the system.The GST rate 18% hard-coded in seven files.
KISS (Keep It Simple)Prefer the simplest design that meets the requirements.A plugin framework for a script used once a semester.
YAGNI (You Aren't Gonna Need It)Do not build features until they are actually needed (from Extreme Programming).Adding multi-currency support "just in case" to a college canteen app.
Law of DemeterA method should talk only to its close collaborators, not reach through chains of objects.order.getCustomer().getAddress().getCity().getPincode()
Composition over inheritanceBuild behaviour by combining objects rather than deep class hierarchies.A five-level inheritance tree that is hard to change.

These principles sometimes pull in opposite directions. Applying Open/Closed everywhere can violate KISS and YAGNI. Good design is about judgement: apply extension points where change is likely, keep everything else simple.


Common Mistakes

  • Confusing abstraction with information hiding. Abstraction decides what to show; information hiding prevents access to what is not shown. They support each other but are not the same.

  • Thinking encapsulation = getters and setters for every field. Public setters for all fields expose the internals anyway. Hide the decision, not just the variable.

  • Over-engineering. Interfaces and factories for code that will never change make the design harder to read, not better.

  • Treating "is-a" in the real world as a reason to inherit. The Square/Rectangle case shows that behaviour, not vocabulary, decides inheritance.

  • Skipping design in Agile projects. Agile reduces big up-front design, but design still happens continuously, through refactoring and short design discussions each iteration.


Interview and Exam Questions

Q1. What is the difference between abstraction and refinement?

Abstraction hides detail to let us reason at a higher level. Refinement is the process of progressively adding detail, moving from a high-level statement towards code. Design moves between them: we describe a module abstractly, then refine it.

Q2. Who proposed information hiding, and what should a module hide?

David Parnas, in his 1972 paper on decomposing systems into modules. A module should hide a design decision that is likely to change, such as a data structure or algorithm, behind a stable interface.

Q3. State the Open/Closed Principle and give an example.

Software entities should be open for extension but closed for modification. Example: new discount types are added as new classes implementing a Discount interface, without editing the checkout function.

Q4. Why is Square extending Rectangle a classic LSP violation?

Code written for Rectangle assumes width and height can be set independently. A Square must keep them equal, so substituting it changes the result (area 16 instead of 20). The subtype is not behaviourally substitutable.

Q5. Which two measures are used to judge functional independence?

Cohesion (should be high) and coupling (should be low). See Modularity, Coupling & Cohesion.

Q6. How does Dependency Inversion make code easier to test?

Because the high-level class depends on an abstraction and receives the concrete object from outside, a test can inject a fake or mock (like FakeSender) and check behaviour without real email servers, databases or networks.


Summary

  • Design turns requirements into a blueprint: components, responsibilities, interfaces and relationships. It happens at the architectural (HLD) and detailed (LLD) levels.

  • Core concepts: abstraction, stepwise refinement, modularity, information hiding, separation of concerns, functional independence, refactoring and patterns.

  • Top-down starts from the whole system; bottom-up starts from reusable parts; real projects mix both.

  • Function-oriented design uses DFDs and structure charts; object-oriented design uses UML.

  • SOLID: Single responsibility, Open/closed, Liskov substitution, Interface segregation, Dependency inversion. Plus DRY, KISS, YAGNI and the Law of Demeter.

  • Next, Modularity, Coupling & Cohesion shows how to measure the quality of a modular design.