Sathvik Oop
Sathvik Oop
Definition:
Every class should have one and only one reason to change. This principle ensures that a class has a
single responsibility or functionality.
Violation of SRP:
Consider a FinancialReport class that generates, saves, and emails financial reports:
class FinancialReport:
print("Report generated.")
Adhering to SRP:
class ReportGenerator:
print("Report generated.")
class ReportSaver:
Definition:
Classes should be open for extension but closed for modification. This encourages extending
functionality via inheritance or composition rather than altering the class itself.
Violation of OCP:
class TaxCalculator:
if tax_type == "GST":
else:
Adhering to OCP:
class TaxCalculator:
pass
class GSTCalculator(TaxCalculator):
Now, adding a new tax type requires only a new class, not modifying the existing ones.
Definition:
Derived classes must be substitutable for their base classes without affecting the functionality of the
program.
Violation of LSP:
class Shape:
def area(self):
pass
class Rectangle(Shape):
self.width = width
self.height = height
def area(self):
class Square(Rectangle):
super().__init__(side, side)
Here, Square inherits from Rectangle but overrides its behavior inconsistently, violating LSP.
Adhering to LSP:
class Shape:
def area(self):
pass
class Rectangle(Shape):
self.width = width
self.height = height
def area(self):
class Square(Shape):
self.side = side
def area(self):
Definition:
A class should not be forced to implement methods it does not use. Instead, use smaller, specific
interfaces.
Violation of ISP:
class FinancialOperations:
def calculate_interest(self):
pass
def process_transaction(self):
pass
def generate_statement(self):
pass
Adhering to ISP:
class InterestCalculator:
def calculate_interest(self):
pass
class TransactionProcessor:
def process_transaction(self):
pass
class StatementGenerator:
def generate_statement(self):
pass
Definition:
High-level modules should not depend on low-level modules. Both should depend on abstractions.
Violation of DIP:
class PDFReport:
def print(self):
class ReportPrinter:
def print_report(self):
pdf = PDFReport()
pdf.print()
Adhering to DIP:
Introduce an abstraction:
class Report:
def print(self):
pass
class PDFReport(Report):
def print(self):
class ExcelReport(Report):
def print(self):
class ReportPrinter:
self.report = report
def print_report(self):
self.report.print()
Conclusion
By applying SOLID principles, the financial management system is modular, maintainable, and
extensible. Each principle ensures clear separation of concerns, flexible designs, and adherence to
best practices in object-oriented programming.