LLD Notes
LLD Notes
1.What is Low‑Level Design (LLD)?
2. Gaps:
● No identification of classes/entities (User, Rider, Location, Notification, Payment).
● Omits data security (masking phone numbers).
● Missing integration points (notifications, payment gateways).
● No consideration for scaling to millions of users.
2. Maintainability
● New features shouldn’t break existing ones.
● Code should be easy to debug and locate bugs.
3. Reusability
● Write loosely coupled, “plug‑and‑play” modules (e.g. generic notification or matching
algorithms usable across apps like Zomato, Swiggy, Amazon delivery).
● Features Introduced:
○ Functions for code reuse
○ Control structures: if-else, switch, for/while loops
○ Blocks for grouping statements
● Advantages:
○ Improved readability over assembly.
○ Modularized small to mid-size programs.
● Limitations:
○ Poor real-world mapping: Difficult to model complex entities (e.g. a
ride-booking system’s users, drivers, payments).
○ Data security gaps: No built-in access control—everything is globally visible.
○ Reusability & scalability: Functions alone can’t enforce consistent interfaces or
safe extension.
Abstraction hides unnecessary implementation details from the client and exposes
only what is essential to use an object’s functionality.
● Driving a Car
○ What you do: Insert key, press pedals, turn steering wheel.
○ What you don’t need to know: How the fuel-injection system works, how the
transmission synchronizes gears, how the engine control unit computes ignition
timing.
○ Abstraction in action: The car provides a simple interface (“start,” “accelerate,”
“brake”) and conceals all mechanical complexity under the hood.
● Using a TV or Laptop
○ What you do: Press buttons on a remote or click icons.
○ What you don’t need to know: How the display panel refreshes, how the CPU
executes machine code, how the OS schedules tasks.
○ Abstraction in action: A graphical interface abstracts away thousands of
low-level operations.
● Key Points
○ The Car class declares what operations must exist but hides how they work.
○ No code for startEngine(), etc., lives here—only signatures.
○ Clients use Car* pointers without needing concrete details.
6. Benefits of Abstraction
1. Simplified Interfaces: Clients focus on what an object does, not how it does it.
2. Ease of Maintenance: Internal changes (e.g., switching from a V6 to an electric motor)
don’t affect client code.
3. Code Reuse: Multiple concrete classes can implement the same abstract interface (e.g.,
SportsCar, SUV, ElectricCar).
4. Reduced Complexity: Large systems are easier to reason about when broken into
abstract modules.
Encapsulation bundles an object’s data (its state) and the methods that operate on
that data into a single unit, and controls access to its inner workings.
● Medicine Capsule
○ The capsule holds both the medicine (data) and its protective shell (access
control).
○ You swallow the capsule without exposing its contents directly.
● Car Odometer
○ You can view the mileage but cannot tamper with it via the dashboard interface.
● Purpose: Allow controlled mutation with checks, rather than exposing fields blindly.
○ Common attributes:
■ Brand
■ Model
■ IsEngineOn
■ CurrentSpeed
○ Common behaviors:
■ startEngine()
■ stopEngine()
■ accelerate()
■ brake()
● Child Classes:
● public:
● protected:
● private:
2. Polymorphism
2.1 What is Polymorphism?
● Scenario 1:
● Scenario 2:
Example:
class ManualCar {
void accelerate(); // no parameter
void accelerate(int speed); // with parameter
};
● Allows the same behavior to adapt based on passed arguments.
Rules:
● Return type: Can be same or different (but not used for overloading)
● Parameters:
● Resolved at runtime.
Example:
class Car {
virtual void accelerate() = 0; // Abstract
};
class ManualCar : public Car {
void accelerate() override; // Manual-specific logic
};
class ElectricCar : public Car {
void accelerate() override; // Electric-specific logic
};
Additional Concepts:
● Protected:
● Homework:
-abstaine
3
#
Class Name
class car &
I
brand ; t
String
model ;
string
(C !
int
engine
start Engine () ;
stop Engine() ;
accerate () ;
brake() ;
3
Generic Class
-
abstruct
=
ClassName
-
: dT
# method 21)
Associations
-
-
-
- object
class
Association
↑
-
Association
*
↓
Inheritance Nat
~
simple gregation
composition
Association
u
Composition
Inheritance
-
Tsis-a relationship
'
sended by (-)
clas Ad
D
[
Animal
I() ;
method
↓ h
3
class B : Public AS
· Fierhuman
C
method 2 ;
main([
·
I
B
*
b new BD ;
>
=
bemethod (C) ,
be methor ;
-
Composition
-
(has-a) relationship
L Denoted by ( -
) >
Association
Semple
FEn
Negation
T
↓
#
*
O O Ob
0
0b3 Container
Composition
=
Ey
-a Code
composition
-
in
main()[
class AS
I
I
+
B b new Bl ;
1(2 ;
=
method
be method2 ;
3 method 1()
b - a - ;
clas B E -
3 -
1
*
A a
;
BL) E
I new All ;
a=
method 2)
;
Sequence Diagrams
-
-
communication/
interaction
① object
Recenting
.
*
- - -
②eline
* B
!
nation
E
·
a
①sag *
Sync
Async
L * B
may
ii
③
Cde&
Destroy Message
-
Create >
-
"juni
!
Destroy >
-
ebay
↓
!
⑥ found My
a
last go
I found rounds
>
Best
F
lost
= >
-
!
↑
Flow
TM
Transaction
- >
Entransaction
Cace, ant
Cace ,
amount) · ② Verily Account
⑤
-Aransaction
Tell Cash
② Dispenser
for money
-
ence
Diam is
②
Object ATM
user
Transaction
Account
Cash Dispenser -
③Diagram
M Etount
penser
fi
i "
I
D
Withdraw (amount,
accNo)
;
-Fransaction
(among
TheckAmt
-
- -
f
-
return tre
*
withdrawlash Camt
--------
D
S 8------------
! I
return amount return amount ↑
.
alt : Cif-elu)
option : (if]
loop :
for/while
Lecture 6 : SOLID Principles Part-2
1. Recap of SOLID Principles
Before diving into the remaining two principles (Interface Segregation and Dependency
Inversion), a quick recap:
We have already covered SRP, OCP, and LSP conceptually. What follows is a detailed
breakdown of LSP guidelines, then full explanations of Interface Segregation Principle (ISP)
and Dependency Inversion Principle (DIP) with illustrative examples.
● Inheritance ensures that subclasses have the same methods, but not necessarily the
same behavior or contractual guarantees.
● Without clear rules, a subclass may override a method incorrectly (e.g., throwing
unexpected exceptions, changing return values or method signatures), causing client
code to fail.
LSP compliance hinges on three broad categories of rules, each with sub-rules:
Ensure that method overrides preserve the contractual interface of the parent:
Ensure that the subclass preserves key “properties” of the parent class:
● Always check whether a subclass truly behaves like its parent, not just whether it
compiles.
● Remember: Signature, Property, and Method rules each have clearly defined
sub-rules—use these as a checklist when designing hierarchies.
● Violations often manifest as unexpected exceptions, incorrect return values, or broken
invariants.
● A single interface/class that includes every conceivable method (e.g., both 2D and 3D
shape operations) forces some implementers to override methods they don’t need.
● Unneeded methods often either throw exceptions or remain unimplemented, hurting
maintainability and violating SRP.
3.2 Illustrative Example: Shapes
“Fat” Interface Approach
// See Code for example
1. Problem: Square and Rectangle are forced to implement volume(), leading to stubs
or exceptions.
3DShape
class ThreeDShape {
public:
virtual double area() = 0;
virtual double volume() = 0;
};
class Cube : public ThreeDShape {
// ...
};
Benefits:
● A high-level class (e.g., UserService) that directly calls concrete low-level classes
(SqlDatabase, MongoDatabase) becomes tightly coupled.
● Changing the low-level implementation (e.g., swapping MongoDB for Cassandra) forces
modifications in the high-level class—violating OCP.
class Persistence {
public:
virtual void save(const User& u) = 0;
};
class UserService {
private:
Persistence* db; // injected dependency
public:
UserService(Persistence* p) : db(p) { }
void storeUser(const User& u) { db->save(u); }
};
Dependency Injection
By following these LSP guidelines and applying ISP and DIP judiciously, you’ll write cleaner,
more robust object-oriented code that stands the test of evolving requirements.
#Cloo
- Singleton ↑
Singleton)
=
Singleton)7 Music/ Singleton
Song
N
player Facade
#7
-·
-
-
Application
Player Music
7
carPL ;
7
-
↑
map
j
<Song] songs string path ;
I
·
vector ;
create
Playlist (string egy
L"Getter selt
&
,titles
da4
create Sony (string ConnectDevice
(Devicetype prame ,
set
:
create
playlist (name) 1) .
-p load
playlist (string name) [ 3
.
I
add Song(prame ,
snamisi play Song (Song song) 23
pause Song (Sony song)
2 ] -
11 Other Methods
Call different
playAll () 2-]
J play
L
to
Strateagypli
class
reNext2 3
.
Il Getter & Settors
-
↓
has Next 1) ;
-
Singleton has Previous() ;
·
I
F
bause() , 2 3 .
g
I
get Device()E3
↓
-
I Sequential Play
Playlist pe ;
I
& factory]
evice
-
#Mandom
-
State
(Deviatya Device blaysound via Bluetooth
play a
,
Lee ,
-
Set
playlist (Playlist pe
-
implementations/
Above
via Cable
Ap
playsound
wired Speaker
Headphones Adapter *
-
set
antom playstatea
playlist (Playlist
&
pla
I
Headphones APA
LAbove
ho ;
↑
implementations
UML
Standard :
-Fab
; 9
Fusi
Standard Def :
-
provides a
surrogate or placeholder
proxy pattern
The
>
- Remote Proxy
>
-
virtual proxy
.
>
- protection proxy
F
=
E cred
series
9 ↑
- .
- J to perh
=
- >at seriee
9 ↑
· Date
e
Distraion
Remote
Virtual Peroxy
=>
it is
= display () &
a a par
:
[ iblidis nullphs)
==
Proxy
Ecotection
abstruct
#
most
·
ja ↑
=
LLD Practice Problem:
Image Editor
Problem: (Easy)
See the UML Diagram below.
This class has some problems:
1. Currently class is maintaining multiple responsibilities.
2. Not scalable (I need to break OCP to add new type of filter or new type of Database)
Functional Requirements:
1. Apply SOLID principles to handle the above problem.
Expectations:
UML + Code (Imagine simple console based void implementation for each method)
LLD Practice Problem:
Sorting Context
Problem: (Easy)
Functional Requirements
Non-Functional Requirements
1. Extensibility
○ It must be easy to add new algorithms (e.g. Heap-Sort) without modifying existing
code (Open/Closed).
2. Plug and Play Model
○ The strategies should be plug and playable easily.
3. Performance
○ Sorting large datasets should remain efficient (average O(n log n) time).
Expectations:
UML + Working Code.
Anti-Patterns
,
· no mic)
"Hello",
String =
③ Hard-coding this
-
(over-enginessing
-
④ Gold-plating
--
7
-
5
Guy .
NOT Repeat Yourely
⑤ LIRY (DO
a
mm
3
Ourloading
⑥ Cred
Getter/setter
⑦ Overs of -
ale
Y it woo
Bematis Optimization
⑧ -
then make it fast
overup ,
Inheritance
⑨
Noter
Patte an ob
③ obl-mic) ;
-
if)
-
er-
-
[3
12
&
conditionals
Replace F
Polymaphism
g
with
⑧, mis
#Find Abstrate
.
# Pubd mish
m
11 empty
I1 defat
return e
Strategy
F Exempty
Command
* man Nob
=ment
Nobl
empis