Explanation
- Loose Coupling: Reduces dependencies between objects, making the system more flexible and easier to maintain.
- High Cohesion: Ensures that a class or module is focused on a specific responsibility, improving clarity and maintainability.
Steps
- Achieve loose coupling by minimizing direct dependencies between objects. Use interfaces or abstract classes to decouple components.
- Achieve high cohesion by ensuring that each class has a well-defined, singular responsibility.
class Printer:
def print(self):
print("Printing...")
class Computer:
def __init__(self, printer):
self.printer = printer # Loose coupling (dependency injection)
def print_document(self):
self.printer.print()
printer = Printer()
computer = Computer(printer)
computer.print_document() # Output: Printing...