S for Single Responsibility
Mistake:
Fat Controllers and Models
Developers often cram too much logic into controllers and models, making them hard to maintain and test.
Solution:
Suggests that a class should have only one reason to change, meaning each class should only have one responsibility.O for Open–Closed
Mistake:
Modifying existing code to add new functionality
Developers sometimes directly modify existing classes to add new features, which can introduce bugs and make the code harder to maintain.
Solution:
States that software entities should be open for extension but closed for modification.L for Liskov Substitution
Mistake:
Subclasses that do not adhere to the contract of their base classes
Developers may create subclasses that override base-class methods in ways that change their expected behavior, leading to bugs.
Solution:
States that subclasses should be substitutable for their base classes without altering the correctness of the program. Ensure that subclasses override methods in a manner consistent with the base class.
Example:
Violation of LS
class Bird
{
public function fly()
{
// Fly logic
}
}
class Penguin extends Bird
{
public function fly()
{
throw new Exception("Penguins can't fly");
}
}
Adhering to LS
interface Bird
{
public function move();
}
class FlyingBird implements Bird
{
public function move()
{
// Fly logic
}
}
class Penguin implements Bird
{
public function move()
{
// Swim logic
}
}
I for Interface Segregation
Mistake:
Implementing large interfaces
Developers sometimes create large interfaces with methods that implementing classes don't need, leading to unused code.
Solution:
Suggests that clients should not be forced to depend on interfaces they do not use. Create smaller, more specific interfaces.D for Dependency Inversion
Mistake:
High-level modules depending on low-level modules
Developers often make high-level classes depend directly on low-level classes, which makes the code rigid and hard to change.
Solution:
States that high-level modules should not depend on low-level modules, but both should depend on abstractions. Use dependency injection to adhere to DIP.
Top comments (0)