0% found this document useful (0 votes)
59 views6 pages

SOLID Principles Cheat Sheet

The document outlines the SOLID principles of software design, providing definitions and examples for each principle. It includes the Single Responsibility Principle, Open/Closed Principle, Liskov Substitution Principle, Interface Segregation Principle, and Dependency Inversion Principle, along with bad and corrected code examples for clarity. These principles aim to improve code maintainability and flexibility.

Uploaded by

ester.xhh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views6 pages

SOLID Principles Cheat Sheet

The document outlines the SOLID principles of software design, providing definitions and examples for each principle. It includes the Single Responsibility Principle, Open/Closed Principle, Liskov Substitution Principle, Interface Segregation Principle, and Dependency Inversion Principle, along with bad and corrected code examples for clarity. These principles aim to improve code maintainability and flexibility.

Uploaded by

ester.xhh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

SOLID Principles Cheat Sheet (With

Code Structure Examples)


SOLID Principles Cheat Sheet (With Code Structure Examples)
1. Single Responsibility Principle (SRP)

Each class should have one responsibility or reason to change.

Bad Example:
class Report:

def __init__(self, content):

[Link] = content

def save_to_file(self):

with open("[Link]", "w") as f:


[Link]([Link])

Corrected Example:
class Report:

def __init__(self, content):

[Link] = content

class ReportSaver:

def save_to_file(self, report):

with open("[Link]", "w") as f:


[Link]([Link])
2. Open/Closed Principle (OCP)

Software should be open for extension but closed for modification.

Bad Example:
def calculate_area(shape):

if shape["type"] == "circle":
return 3.14 * shape["radius"] ** 2

elif shape["type"] == "rectangle":


return shape["width"] * shape["height"]

Corrected Example:
class Shape:

def area(self):

pass

class Circle(Shape):

def __init__(self, radius):

[Link] = radius

def area(self):

return 3.14 * [Link] ** 2

class Rectangle(Shape):

def __init__(self, width, height):

[Link] = width

[Link] = height

def area(self):

return [Link] * [Link]


3. Liskov Substitution Principle (LSP)

Subtypes must be substitutable for their base types without breaking behavior.

Bad Example:
class Bird:

def fly(self):

pass

class Ostrich(Bird):

def fly(self):

raise Exception("Can't fly")

Corrected Example:
class Bird:

def move(self):

pass

class Sparrow(Bird):

def move(self):

print("Flying")

class Ostrich(Bird):

def move(self):

print("Running")
4. Interface Segregation Principle (ISP)

Clients should not be forced to depend on methods they do not use.

Bad Example:
class Machine:

def print(self): pass

def scan(self): pass

def fax(self): pass

Corrected Example:
class Printer:

def print(self): pass

class Scanner:

def scan(self): pass

class FaxMachine:

def fax(self): pass


5. Dependency Inversion Principle (DIP)

Depend on abstractions, not on concretions.

Bad Example:
class LightBulb:

def turn_on(self): print("On")

def turn_off(self): print("Off")

class Switch:

def __init__(self):

[Link] = LightBulb()

def operate(self):

[Link].turn_on()

Corrected Example:
class Switchable:

def turn_on(self): pass

def turn_off(self): pass

class LightBulb(Switchable):

def turn_on(self): print("On")

def turn_off(self): print("Off")

class Switch:

def __init__(self, device: Switchable):

[Link] = device

def operate(self):

[Link].turn_on()

Common questions

Powered by AI

The issue with the initial Bird and Ostrich example is that the Ostrich class, which inherits from Bird, throws an exception when its 'fly' method is called, violating LSP. The correction involves changing the method to 'move' and ensuring all subclasses implement it appropriately, allowing subtypes to be substituted without breaking functionality .

Applying SOLID principles, such as the Single Responsibility Principle (SRP), enhances software design by making systems more modular, reducing the impact of changes. SRP, for instance, limits each class to a single responsibility, which simplifies code maintenance, promotes clarity, and minimizes the potential for introducing errors when updating features .

Dependency abstractions allow high-level modules to remain flexible and unconstrained by specific low-level module implementations. The document demonstrates this with the 'Switchable' interface, representing an abstraction that the 'Switch' depends upon, not the concrete 'LightBulb.' This practice facilitates easier integration of different 'Switchable' devices .

The Interface Segregation Principle is highly applicable in real-world scenarios where interface broadness can impose undue burdens on implementing classes. For instance, initially combining print, scan, and fax functions into a single 'Machine' interface could force classes to implement unused methods. By segregating into smaller interfaces ('Printer', 'Scanner', 'FaxMachine'), developers achieve more focused and user-centric implementations .

DIP promotes high-level modules depending on abstractions rather than specifics of low-level modules. In the example, the 'Switch' class initially depends directly on 'LightBulb.' By introducing a 'Switchable' interface, 'Switch' now relies on this abstraction, thereby allowing various devices to be controlled by 'Switch' without altering its implementation .

The corrected example demonstrates improved extensibility by adding new shapes without modifying the existing code structure. By using a base 'Shape' class with an abstract 'area' method, developers can extend functionality with new shape classes like 'Circle' and 'Rectangle,' thereby enhancing the system's capacity to handle future extensions seamlessly .

SRP can be violated when a class has more than one reason to change, such as combining unrelated functionalities. In the example provided, the 'Report' class handles both content and file-saving, violating SRP. The corrected approach separates these responsibilities into two classes: 'Report' for content and 'ReportSaver' for file saving .

The OCP is maintained by designing systems that allow existing code to be extended without modification. Polymorphism is used to achieve this by creating a base 'Shape' class with an 'area' method and extending it with specific classes like 'Circle' and 'Rectangle', allowing new shapes to be added without altering existing code .

ISP helps prevent clients from being forced to rely on interfaces containing methods they don't use. The document presents an initial 'Machine' interface with print, scan, and fax methods, imposing unnecessary dependencies. The corrected approach separates these functionalities into distinct interfaces ('Printer', 'Scanner', 'FaxMachine'), allowing clients to utilize only the necessary components .

By appropriately distinguishing subclasses, the system avoids unexpected behaviors when subclasses are substituted for their parent classes. In the example, redefining behavior with a 'move' method ensures 'Sparrow' and 'Ostrich' can substitute 'Bird' without causing errors, maintaining system integrity and consistent functionality .

You might also like