Docsity

Low Level Design (LLD) Handbook: OOP, SOLID, UML, Design Patterns & C++ Interview Notes, Study notes of Systems Design

Partial preview of the text

Download Low Level Design (LLD) Handbook: OOP, SOLID, UML, Design Patterns & C++ Interview Notes and more Study notes Systems Design in PDF only on Docsity!

FAANG - PRODUCT - SYSTEM DESIGN INTERVIEWS LOW-LEVEL DESIGN * HANDBOOK * A Complete Visual Guide to Object-Oriented Design, SOLID, UML, Design Patterns, Modern C++ and Real-World ect Problems Fina WHAT'S INSIDE} -=---====------2---0-nnennnen nen nne ' Cr) Foundations of LLD 2-10 Structural Patterns 61-70 Ci) OOP Mastery “1-20 Behavioral Patterns 1-84 ' Ci) SOLID Principles : : 21-30 Modern C++ for LLD 85-95 ‘ UHL & Design Communication 31-40 Core LLD Problems 96 - M10 Design Principles 41-50 Advanced LLD Problems M1 - 120 Creational Patterns 2 : 51 - 60 120 hand-crafted visual pages - C++ code examples - UML diagrams - Interview checklists "Design is not just what it looks like. Design is how it works" *& How To Use This HANDBook This handbook is your complete roadmap to master (LLD) for interviews. 4. LEARNING SEQUENCE Understand OOP fundamentals Learn SOLID principles Study Design Principles Learn Design Patterns Practice LLD Problems Master C++ for LLD Do Mock Interviews Build Strong base Write good designs Think like a designer Solve recurring problems Apply concepts Implement clean code Et SOICIOIGIONOIC) Become interview ready 2. How To STUDY EACH ToPIc 1 Read the intuition carefully. (Formula >, 1 Understand the diagram / visual. i ela | 1 Go through the Key concepts. ' ' 1 Study the code example in C++. | Implement | i 1 Try to implement it yourself. ' pice 1 1 Solve the related interview problems. 1 v ! 1 Note down mistakes & important points. | Rae 1 r 1 1 Revise using the cheat sheets. 1 Mates! 3. How To PRACTICE * Solve problems without seeing the solution. * Draw class diagrams and sequence diagrams. * Try different approaches. © Discuss with peers / friends. © Do mock interviews (verbal + coding). Practice : ; i Makes © Focus on design quality, not just code. Perfect ! jernees Low-Level System Design 4, INTERVIEW PREPARATION STRATEGY % Be clear with requirements. % Identify classes, responsibilities and relationships. + Keep design simple & extensible. + Apply SOLID principles. + Use design patterns only when needed. + Write clean, modular and reusable code. + Always think about edge cases & scalability. | Communicate your thought process clearly. 5. WHAT You WILL MASTER OOP & SOLID principles All important Design Patterns UML diagrams C+ implementation Core LLD problems Advanced LLD systems Extensibility & Scalability Concurrency & Thread Safety Tnterview communication v v v v v v v v v * Everything you need for FAANG / Product interviews. Page oh 6. YouR RoADMAP (OVERALL) Foundation i Design Patterns OoP, SOLID, Design Principles Creational , Structural , Behavioral Class; “Sequencey State, Activity Modern C++, Smart Pointers, RAIL, Thread Safety Parking Lot, Elevator, Core LLD Problems \ ATM, Winding Mochi Chess, ete. } Splitwise, Logger, Cache, Rate Limiter, File System, ete. Practice, Analyze, Improve, Repeat | “Design is not just what it looks like and feels like. Design is how it works: — Steve Jobs te Requirement GATHERING Pagel \ Requirement gathering is the first and most important % 3. Types oF REQUIREMENTS % 6. How To ASK GooD QUESTIONS step in LLD. A good design starts with a clear eh Whale te cere? understanding of what the system should do. Reupenetts © What all actions can a user perform? © Are there any different user roles? © What is the expected load? © Are there any performance expectations? & 1. FUNCTIONAL REQUIREMENTS Constraints Functional, These define what the system should do. Non-Functional (How well) Example (Movie Ticket Booking System): bee) (Uiritations) Piha harpens ticace crete? © Users can search movies. 7 oe, © Performance Technology © Do we need to support multiple platforms? © Users can view show timings FUNCTIONS tunes © Scalability © Budget © Are there third-party integrations ? * Users can select seats. ica a yece nents 2 abil + Time © What are the constraints (time, budget, tech)? © Users can book tickets. ey — | © Security + Resources © Are there any future expectations? © Users can cancel. bookings, xy— OR) Segal (Compliance Se ee ee # System should generate ticket. | Good questions * Users can view booking history. + UR CORES | lead to great designs ! @ Admin can add/update movies, shows. —<—— ee ae ee © Support multiple payment methods. > Technology stack: C++17, STL, MySQL > Budget: Low & 7. EXAMPLE CONVERSATION ke 2. NoN-FUNCTIONAL REQUIREMENTS > Time: 3 months Interviewer: Design a Parking Lot. These define how well the system should work. > Team size: 3 developers — © Performance (responce, time <2 sec) | = Eee een an ; 2: Can you please confirm the requirements? © Scalability (handle 10,000 users) QUALITY ‘h P viewer Sure. © Availability (99.9% uptime) ann ® What types of vehicles? —> Car, Bike, Truck © Security (secure payments, data privacy) 4 5. Good _vs BAD REQUIREMENTS ® How many floors? +> Multiple (maybe 5) © Usability (easy to use UL) ete | | @® Payment system? + —> Cash, Card, Online * Maintainability (clean and modular code) ( Goop REQUIREMENTS BAD REQUIREMENTS @ Delve weed Weckirg wm adaree? = No © Reliability (no dota less) Vidor ad! spate X Vague © Should we support EV charging? +> Yes * Platform (Web, Android, iOS) s ® Any time limit for parking? > —> Yes ae Re Astiguess @ Is ticket required? + Yes || v Achievoble X Conflicting est TIP: | | ¥. Consistent Se Uneealistig: Ula: lel ls a ae ee 2 Always ask questions. Good requirements lead Y Verifiable X Not testoble | He Clarify before you design i to a good design. Don’t assume! V. Priovitized X Missing constraints ! Assume less, Confirn more! © (5.} LLD Interview FRAMEWORK oe A strong LLD design follows a clear and repeatable process. We DETAILS oF EACH STEP tk \VISUAL_FRAMEWORK This framework helps you think like a designer and @ Clarify Requirements communicate like a professional. * Ask questions, remove ambiguities. + + Identify scope and assumptions. Clarify 7 Requirements / 3 ® Identify Actors + Understand the problem @® Identify Actors Write clearly. * Who are the users? Identify Core Entities © Any external systems / services? Who will interact with the system? @® Identify Core Entities + Use Noun Technique. Identify Identify the important Entities nouns (classes). List all important classes. @ Define Responsibilities Follow Single Responsibility Principle. Decide “who should do what”. Define Relationships IS-A, HAS-A, USES-A, DEPENDS-ON. Association, Aggregation, Composition. Define public methods. © Define Interfaces and interactions. Assign responsibilities to classes. Define how classes ® relate to each other. Relationships Define methods for each class. Keep interfaces simple and clean. : Use patt ly whe Apply Design Patterns os ite a @® Apply Design Patterns 3k KEY GUIDING PRINCIPLES * Pick patterns thot solve a design problem. ‘ , on eae ee tc ge eae opie | & Understand the problem first. Handle Edge “Cases Think of exceptions, + Don't use patterns just for the sake of it. invalid inputs, limits. @® Handle Edge Cases & Keep the design simple. Good design © Involid is Jn ue @ Follow SOLID principles. ; jets ExcenniiCty How will the system 0 inpbte Tbenndey yeuciues ad a pa hgh is not about ee anti * Failure scenarios, concurrency. & Prefer composition over inheritance. perfect rendes @ Discuss Extensibility & Lew coupling, High cohesion. Tete eeu Write Code Implement clean, modular * New features, new roles, new rules. ote ie coe te ee neva! and testable code. + Keep the system open for extension. 3 o w ight structure. & Communicate clearly. @® Write Code Clean, modular, reusoble, testoble code & Think in objects, not in functions. Follow coding best practices. YN INTERVIEW TIP: Y > Take interviewer along your thought process. > TR's okay to make changes as you design. te “A great design today makes future changes easy.” © Opsect RELATIONSHIPS Page 8 Relationships define how classes are connected %& LEGEND Ye RELATIONSHIPS SUMMARY and work together. ae Inheritance (IS-A) Type SymBot | MEANING EXAMPLE tk Types oF RELATIONSHIPS — Aggregation (HAS-A) — eee Inheritance Dog IS-A oe Composition (HAS-A) IS-A ae : @) IS-A (Inheritance) Gis a type of) | Animal Fan hicte ts A———pp | | =eeess > Uses-A is a type of B. 7 { % Strong velationship, =P > Depends -On HAS a Weak ownership | Team HAS-A neaition (Aamescian)| i [Ges Player HAS-A (Ac tion) @ - seregonion KO 6 HAS-A Strong ownership | House HAS-A has B A Exampce Diagram ~ ONLINE SHOPPING SysTEM (Composition) (part of) Roorn Weok ownership. Uses os parameter | Order USES-A User @) HAS-A (Composition) A ea USES-A | - A has B. or temporary Payment Strong, ownership. A a ae Customer Admin DeliveryAgent Jepends on Report DEPENDS-ON B cannot exist without A. | eta | [ “ 3 DerennSeGutl eee ECs nay wh affect) a 1 @) USES-A (Association) % | delivers ye Saere >B OF Cort H es Gea Suen A uses B as a parameter [ Onder | Assocratton | ——— or temporary. connection Class ©) DEPENDS-ON (Dependency) , ss | ee e=-- A depends on B. AE iia pa % Notes Araschanges ing Boi OrderTtem | Inheritance models “isa” relationship affect A. ; | + Composition represents whole-part with strong ownership. © ASSOCIATION nN B © Aggregation is a weaker form of composition. * Association is a general connection. Dependency is the weakest form of relationship General connection between A and B. Interview TIP: Explain the reason for choosing the relationship. INTERVIEW TIP: Example: We use Composition between Order and OrderTtem because OrclerIter cannot exist without Order. S) / Always prefer Composition over Aggregation, “The right relationship makes your design flexible, maintainable ond extensible.” ©, and Aggregation over Association/Dependency, when the relation is strong and critical. COHESION & CouPLING Good design aims for High Cohesion + 1. Hich Coneston ¢ A closs has related responsibilities that belong together. * Every method works toward a single, well-defined purpose. e Easier to understand, maintain and test. 2. Low Courtine © Classes have minimal dependencies and Low Coupling. Examete — User Service registerUser() loginUser() updateProfile() changePassword() resetPassword() All methods are related to user management > High Cohesion Exampere - Low Courtine on each other. * Changes in one class have little or no impact on others. ¢ Promotes flexibility, reuse and testability. He 5. Way THey Matter [ OrderService | —““** > [ PaynentGatenay | TPayment (interface) 1 OrderService depends on abstraction (IPayment), not on concrete class. VAY [ © High Cohesion makes Z ry Z classes focused and easy to understand. ZF Low Coupling makes the system flexible and easy to change. ZY Together, they improve maintainability, scalability and testability. They reduce bugs and support future extensions. 7 They are key to building robust, real-world systems. © 3 3. Trait Courtine (Bap) Classes are strongly dependent on each other. Changes in one class break others. Hard to maintain and test. 4. Loose Courtine (Goon) Classes are weakly connected. One class can change without affecting others. Achieved using abstractions, interfaces and DI. * CoHeston vs CoupLina Examece - TieHT Courtine directly OrderService | —“***—>| CreditCardPayment Tf CreditCardPayment changes, OrderService also breaks. Exampce — Loose CoupLine uses — SSS | Payment. (interface) CreditCordPayment. UPTPayment New payment methods can be added without changing OrderService. OrderService Asrect Hicit Conesion / Low Courtine (Goos) | Low Conesion / Hen Courtmne (Bao) Fess |) Dovermc tang ual De many things / depend heavily Change Impact Changes ‘are localized Changes break other parts Maintainability | Easy to maintain Hord to maintain Revsability | High ba Testability Easy to test Hard to test Flexibility Flexible & Extensible Rigid & Brittle He Aim for igh Cohesion and Low Coup! leads to clean design, happy code and successful projects! (©) Part IL — OOP Mastery Ciasses & OBsECTS Everything in OOP revolves around classes and objects. A class is a blueprint, and on created from thot blueprint. we 1. Ciass + A dass is a user-defined type. + Tk acts as a blueprint or template. + Tk defines data (attributes) and functions (methods). No memory is allocated when a class is defined. *% 2. Ossect An object is an instance of o class. ° Tt has its own state (dota volues). Memory is allocated when on object is created. Objects interact with each other by calling methods. we. STATE / ( * State refers to the data or attributes { of an object. Example: brand = “Toyota”, speed = 80 Enoch object has its own state. ) & object is a real-world entity Example (C++) class Cor { private: string brand; int speed; public: void setSpeed (int s) { speed = 5; } void show() { cout << brand << " running at " } << speed <<" km/h” << endl; hs Exampue (C++) int main() { Car cori; cart. setSpeed (80); card.show(); ) Car cord; car2.setSpeed (120); car2.show(); U1 Output: running ot 120 keo/h U1 object of class Cor U1 Output: running at 80 km/h 1 another object return 0; } Ba State \ A. BEHAVIOR Behavior refers to what an card -> brand: Toyota object can do. speeites80 ) car2 > brand: Honda Ve speed: 120 a inside the class Defined by methods (functions) + Example: setSpeed(), show() f { : { \ Cass vs Opgect Page 11 Ctass Ossect Blueprint or template Real-world entity Logical / Conceptual Physical / Runtime entity No memory allocated Memory is allocated Defined using “class” keyword Created from a class Con have many objects Belongs to a class Example: Car (class) Example: carl, card (objects) Reac-Wortp ANALOGY Ctass (Guepeiat) creates Car objects ee | a = speed ~ setSpeed() Sie show() Benavtor &. Ibentity eart.setSpeed (go) | * ‘TWentity meons, that every cart.show() ) abject is unique ) = Even if tuo objects have the ) cord. setSpeed(120) sitie, tike,, thay rare stall card shoul) j different objects. © Example: cart != card program to life! Ossects (Real. Entities) cart brand: Toyota speed: 80 cor2 brand: Honda. speed: 120 cart (address: 0x1001) cord (eddress: 0x1002) Different. memory addresses —> Di al Page 12 (12.] ENCAPSULATION Encapsulation is the wrapping of data (attributes) and methods (behavior) together in a single unit (class) 2. Access Mopirzers (IN C++) and restricting direct access to some of the object’s Modif From Inside From Derived From Outside lodifier Access Class Class Class components. Cass pee Only within vo. x x te 1. Data Hrpine the. the class Public Interface * Hides the internal implementation (yaéthods) eg Within class details of an object. protected | and derived v v x + Prevents accidental modification ee class of data. (attributes) What is hidden © Access to data is provided only from outside public Anyahere Vv WA vA through well-defined methods (public. interface). 4. Goop vs Bap ENCAPSULATION 3. INvARIANTS = f 5. WHEN ENCAPSULATION HeLPs Goon ENCAPSULATION + An invariant is 0 condition that must always be true abo Eten reuntOel When objects have important data that é Sef * Data is private. © Data is public. main in a valid ate. 1c Meee ects torre ee * Access through public..methods. * Anyone con modify directly. must be protected. + Encapsulation helps maintain invariants ttrolli * Validation is ncapst lps riants by controlling Volidati done inside methods. + No. validation, © When you need to maintain invariants. oid deta ee acta ond’ waked: # Object is in a consistent state. ick cowie ayteauvscee ie) Dich cant be neil state © When implementation may change in future. ° AL changes to dota ge through methods that enforce Asse = eee as eet ( J | © When you want loose coupling and better e rules. private: double balance; peeves” maintainability. ple public: Example INVARIANT void depasit(double amt) { double balance; // anyone can change! if (amt > 0) balance += amt; ¥ } double getBalance() const { return balance; } a.balance = -1000; // Inolid state » ©) For a Bank Account: balance >= 0 (cannot be negative) < Encapsulation = Protection Account a} * Control + Consistency. 6) i 1 ' i i | I 1 1 1 i i i | I I | 1 | I h i Hl i i i © H Os Y Interview Trp: Always explain how you will protect data ond expose only what is necessary. ©) wa (14.) INHERITANCE Inheritance is the OOP mechanism where a new class (derived/child) ~ Page 14 acquires the properties and behaviors of an existing class (base/parent). 3 Memon! Oveterone 4. Is-A ReLatronsure 2. Base / Dertvep Ctasses © Derived class can provide its own Fe a ie, implementation of a base class method. © Hebartiandecrepriseits) on SA * Base (parent) cele the existing class whose ne ee a A, relationship. Paeet es ere Munstae same name, same parameters and © Derived class IS-A kind of * Derived (child) class - the new class that same return type. base class. inherits from the base class. © Enables runtime polymorphism. Piccangle Dea, ole AR Anonel: * Base class provides generalization. enn © Derived class provides specialization. ae { | Fuca H Virtual, vail aurdOl 6 i eo H m "Some sound” 5 I Apel Ae ene cau << "Some sound” << endl; | Class Class i 1} |: | Dig) overs | class Dog : public Animal { i Dog Cat Bird | public: a sound() of (Derived) erived) (Derived) } void sound() override { | Animal. | cout << "Bark" << endl; \ | i } 4. Prostems wITH INHERITANCE 5. Example (C++) Was ! ; class Animal { ea ag a ea Saeed @ Tight coupling between base ond derived classes. pubis: © Changes in base class con affect all derived classes: void eat() { cout << “Animal eats” << endl; } oBrealisWencapwulalion. sometimes: yh ‘ = ji F . class Dog : public Animal { ( 1 # Inheritance hierarchy can become hard to maintain public: Inheritance models IS-A relationship: j } (deep hierarchies). - void bark() { cout << "Dog barks” << endl; } SH Code reusability. ate | * Diamond. protien in muligle inheritance a ree | Et Supports. pelqerion = (ep) | Dog ds gene: pln H Use carefully. Overuse leads to | d. bark(); 1 cum method. complex and rigid designs. { return 0; © e J } : ae, a a Pe Inheritance is powerful, but with great power comes great responsibility! (©) = (15.] PoLYMORPHISM Polymorphism means “many forms”. Tt allows objects of different classes to be treated as objects of a common base class through a common interface. 1. WHat ts PotyMorPHIsm? © One interface, mony implementations. © Same method name, different behavior depending on the object. * Achieved through inheritance and method. overriding (or interfaces). 2. Types oF PoLyMoRPHISM @ Compre-time PoLymorPHism (Static / Early Binding) + Achieved by function/method overloading * Resolved by the compiler, © Based on number or type of parameters. @ Runtime PotymorPHrsm (Dynamic / Late Binding) * Achieved by method overriding. © Resolved + Based on object (not reference) type. at runtime. we Tee Prefer runtime polymorphism. Tt makes code more flexible and extensible. © PoLyMoRPHISM 3. Exampce (RUNTIME PoLyMorPHIsm — C++) Page 15 5. How PotymorpHism Works (RUNTIME) Hinclude using namespace std; class Shape { public: virtual void draw() = 0; virtual ~Shape() {} 11 pare virtual function class Circle = public Shape { public: void draw() override { cout << “Drawing Circle” << endl; } 1 class Rectangle public: void draw() override { cout << "Drawing Rectangle” << endl; } public Shape { h void show(Shape* s) { s->draw(); H calls the correct draw() at runtime } int main() { Shape* s} Circle ©} Rectangle r; s = &e; — show(s); s = &r;— show(s); return 0; 3 H. Output: Drawing Circle 1 Output: Drawing Rectangle 4. Exampce (ComPILe-TIME POLYMORPHISM — OVERLOADING) class Calculator { public: int add(int a, int b) { return a + b;} double add(double a, double b) { return a + b;} int add(int a, int b, int c) { return a+ b+e;} h W some method name M diferent poramebers M resolved ob compile time J One Interface Many Implementations, Better Desig draw) (Called through base class reference) ¥ Rectangle::draw() (Implementation) ¥ Circle::draw() (implementation) The actual method is chosen ot runtime based on the object the reference is pointing to. 6. Key Pornrs Polymorphism improves code flexibility. Tk supports loose coupling and extensibility Use virtual functions and method overriding for runtime polymorphism. vi eS @ Base class pointer/reference can point to — “ 2 derived class objects. QAR u N 7. Reac-Wortp ANALocY A person can behave differently in different roles. Example: A teacher can be a mentor, evaluator, or guide — some person, many roles SUMMARY Polymorphism lets you write one interface and multiple implementations The right one is chosen automatically based on the object at runtime. © Oy (16.| COMPOSITION Page 16 aja Composition is a strong “has-a” relotionship where one class contains objects of other class(es) as its parts. If the whole is destroyed, the parts are also destroyed. 4. Wuat 1s Composrtion? 3. Exampce (C++) 4. UML Dracram © Represents a HAS-A relationship Hinclude Car i Whole © The container closs is the owner sing nameepatel sta ee (owner) of the contained objects class Engine { Caiman © Parts have their oun lifecycle but public (ye eee = heed ie ees void start() { cout << “Engine started” << endl; } (filled diamond.) h hi © Achieved by creating objects as date (chee class Car { 1 Cor HAS-A_ Engine Part private Coumed object) 2. Composrtion vs AGGREGATION Engine engine; 1 Composition: Engine is a part of Car oe = public: > Composition Aggregation void startCor() { Bee sus Courostt oa Z S engine. start(); © Better encapsulation. Strong lhat=e weak ahessa cout << "Car is ready to drive!" << endl; & Clasrrecmaake Parts cannot exist Parts con exist } ie sarah daapedrtly ‘ © Improves modularity ond maintainability. - © Reduces the chance of dangling references Tight coupling Loose coupling ink main) { 7 © | Filled diamond (#) | Hollow diamond (O) Car myCar; Lifetime of parts | Lifetime of parts is muta tart Car(s 6. ReaL-WorLD_ ExaMPLes [Hose] depends on whole independent wraburrt 0; } 4 Car has on Engine C= aaa ea , ke House has Rooms | Example H ; | Composition : House has Rooms i pi % Order has Orderltems. [ Room ] WP vAggregalin. , public = Changes in bose affect children ot runtime B void startCort), engneistert(); = NG. siibalilciRen ivilabion: = Slightly more code (need ve a ere i cout << “Car started” << endl; } UeS Ga oe) eat(); inherit d.bork(); 11 Own method Car ¢} Page 17 Dog, Cat, Bird are all types of Animal. Car has on Engine. Engine can exist without Cor. Prefer Composition over Inheritance unless the relationship is clearly IS-A. Key Takeaway: Inheritance says “You are a type of me.” Composition says “You are a part of me.” ®) DEPENDENCY INJECTION Dependency Injection (DI) is a design pottern where an object receives its dependencies from on external source instead of creating them by itself. Tk promotes loose coupling, testability and maintainability. 4. Constructor Ingection 2. Setter Insectron | 3. InterFace Insectron © Dependencies are provided # Dependencies are injected through a. setter method. ee through the constructor. . after abject creation might Ha coo Alisa chara ti dapat after okeek * Glent depends on obstractions, not concrete classes. | 4 © Guarantees that the dependency tyme is aveiloble ond immutable. class Logger { Example: lie: class Logger ( ' void. log(string msg) { cout << mag << endl; } class Logger ( | class UserService { Loose Coupling : Classes are not tightly lie i " ; public: | pode: bound. to concrete implementations. - void log(string msg) { cout << msg << endl; } class jbessiress { virtual wid leglatrng nes) =i Tlocger® loggers as Hq es virtual ~TLogger() {3 i i class UserService { Logger? logger; chi ap Sigh penta | | space 57 UserService TLogger* log) carole as, 2 si Ae as Logger* logger; UserService() : logger(nullpte) as! Pillage «pli Hkaggr “t logger(log) with mocks or stubs for testing. ‘ |) [fy essetect inet public: vid. regjsterUser() { 11 Constructor Tnjection void setLogger(Logger* log) { “s 7 — UserSeritea( Logger lag) ov Uagpartng) eee wid log(string msg) override { lagger->log(“User registered’); Flexibility: Change dependencies without void registerUser() { } cout << "Fle: "<< mag ce endl; modifying the client code. logger->log(“User registered"); void. registerUser() { ) logger ->log(“User registered"); % i 2 % } Reusobility ‘Components, con be reused in | different contexts. F Comstruchor Tajction) ang ear ma Hou it works (Interface Injection) Client | creates UserService Client Une Servica Pilalogger a an 2 a (Main) i Gro logger yet (Wain) | interface pr | per | (depends on TLogger) (CLLogger) gaan ” as | = UserService knows ILegger (abstraction), luster Temneveuetoe | setLogger(logger) eo fr | not FileLogger (concrete). 5. Trees or Depenvency Ingectron - Quick Summary Key Takeaway, Type a wee When te use Pros Cons | ' | He Let the container create and. inject | Constructor Injection Dependencies via constructor Required dependencies, Ensures dependencies are ready, | Connot change dependency i beoce } (ok dhjeck creation) immutable objects strong, immutability ofker creation | pence, Setter Injection Dependencies via selter methods Optional dependencies, Flexible, allows changing Dependency may be missing |. Depa oh (obetenetions, ni catenin (after creation) changeable dependencies dependency not set | He This makes ‘code clean, flesible ond. Interface Injection Dependencies via interface When multiple implementations | Promotes loose coupling, Slightly more setup H easy to test. oO} Cabstraction) ore possible easy to extend Cinterfaces) ee (20.| TIMMUTABILITY Tmmutobility means an object once created, ite state connot be changed. Page 20 Tt helps in writing relioble, predictable ond thread-safe code. 4. Immutaste Oszects 2. Const CorRECTNESS 3. Derenstve CopyInG 4. Tureap Sarety Benerits © An immutable object's state @ const prevents modification of data © Tf a class holds a mutable object © Immutable objects are naturally cannot be modified after creation. by moking voriables, functions or (ike array, pointer, ete,), return thread-safe. 3 AL RASS ae RN ai! RAW oral: objects read-only. copies instead of references. © Multiple threads can read the same No setter matheds; only getters. @ Helps the compiler catch unintended © Prevents external code from SUSE (eeu sneatia: modifications. modifying internal state. @ No risk of race conditions because Glass Point { stake never changes. ESS 1 const. object class Person { const int x; const Point p(2, 3); private: Example (Multiple Threads Reading) const int ys pegetXO; 0K atring nome; Tas public: Wo px = 40; 1 Error: cannot modify public (Read) PointCink x, int y) + xed, yly) (2 // init list aaa cee Person(const string & n) : name(n) {} Immutable int getXO const { return x; } eae f ‘Calle : 1 Return by value Ceopy) Config, Object Osea 2 ink getYO const { vetum ys } Fs se -_ i “a 2 7 string getName() const { return name; } (Read-Only) eed) 1] No setters > state cannot change ks ees Hi Taka tog, volun Ceopy) Thread 3 ‘ 1 const reference void setName(string n) { (Read) void printPoint (const Point & p) { name = nj How it works cout << p.getX << *, * ce p.get¥O} } 11 p canna be modified here % 3 How it works Benefits Summary Create Point (2, 3) } Hl f \ ces item |v. Safe to share across threads | ; Tre | returns COPY | v No unexpected side effects | 1 U conat as a promise that a function | iv | | or object will not change the state. ©| begs 25 -- iv | oe eee ee) } Caller cannot change. | | internal state ‘ Quick Summary Topic What it means Points Example / Note = es F *& Key Takeaway Tmmutable Objects Objects whose state connat be changed Use Final/const fields, no setters Point class with const x, y Sa ee Const Correctness Ensure functions /cbjects de not modify state | Use const with variables, functions, const Point &, getX() const Immutobility leads to predictable, references ond member functions safe and easy-to-mointain code. Defensive Copying Return copies of mutable data Avoid exposing internal state Return string by value, not reference © Thread Safety Benefits | Inmutable objects ore safe in multithreading | No locks needed, no race conditions | Read-only config shared across threads