The SOLID Principles: A Guide to Better Object-Oriented Design
The SOLID principles are five object-oriented design principles that can help you write better code. They are:
- Single responsibility principle
- Open/closed principle
- Liskov substitution principle
- Interface segregation principle
- Dependency inversion principle
The Single Responsibility Principle
The single responsibility principle (SRP) states that every class should have only one reason to change. This means that a class should only be responsible for one thing. For example, a class representing a user should only be liable for storing and retrieving user data. It should not be accountable for logging user activity or sending email notifications.
Code sample:
class User:
"""A class that represents a user."""
def __init__(self, name, email):
self.name = name
self.email = email
def get_name(self):
"""Returns the user's name."""
return self.name
def get_email(self):
"""Returns the user's email address."""
return self.email
The Open/Closed Principle
The open/closed principle (OCP) states that classes should be available for extension but closed for modification. This means that classes should be designed to allow new functionality to be added without modifying the existing code. For example, a class representing a car could be extended to support a new engine type without changing the code that handles the rest of the car’s functionality.
Code sample:
class Car:
"""A class that represents a car."""
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def get_make(self):
"""Returns the car's make."""
return self.make
def get_model(self):
"""Returns the car's model."""
return self.model
def get_year(self):
"""Returns the car's year."""
return self.year
class ElectricCar(Car):
"""A class that represents an electric car."""
def __init__(self, make, model, year, battery_size):
super().__init__(make, model, year)
self.battery_size = battery_size
def get_battery_size(self):
"""Returns the car's battery size."""
return self.battery_size
The SOLID principles are valuable guidelines that help you write better object-oriented code. Following these principles can create more reusable, maintainable, and extensible classes.