SOLID Principles in Apex
By the end of this lesson, you'll be able to:
- Name the five SOLID principles
- Recognize a Single Responsibility Principle violation in a class
- Apply the Open/Closed and Dependency Inversion principles using patterns from Module 11
Prerequisites: "Writing Clean Code"
S — Single Responsibility Principle
// VIOLATES SRP: one class doing validation, calculation, AND email
public class OrderProcessor {
public Boolean isValid(Order__c order) { ... }
public Decimal calculateTax(Order__c order) { ... }
public void sendConfirmation(Order__c order) { ... }
}
A class should have exactly one reason to change. OrderProcessor above would need editing if the validation rules change, if the tax rate changes, or if the email template changes — three unrelated reasons tangled into one class. Splitting it into OrderValidator, TaxCalculator, and OrderNotifier gives each class a single, focused responsibility.
O — Open/Closed Principle
public interface DiscountStrategy {
Decimal apply(Decimal price);
}
public class SeasonalDiscount implements DiscountStrategy {
public Decimal apply(Decimal price) { return price * 0.9; }
}
public class LoyaltyDiscount implements DiscountStrategy {
public Decimal apply(Decimal price) { return price * 0.85; }
}
A class should be open to extension but closed to modification — adding a new kind of discount means writing a new class that implements DiscountStrategy, never editing existing discount classes. This is Module 11's interfaces and polymorphism directly enabling a SOLID principle.
L, I, D — the remaining three, briefly
- Liskov Substitution — a subclass should be usable anywhere its parent is expected, without breaking anything. If
SalariedManager extends Employeebut somehow behaves incorrectly wherever a plainEmployeewas expected, that's a Liskov violation. - Interface Segregation — prefer several small, focused interfaces over one giant one. A class shouldn't be forced to implement methods it doesn't actually need.
- Dependency Inversion — depend on an interface (like
DiscountStrategy), not a specific concrete class — exactly what the Open/Closed example above already does, sinceOrderProcessorcould hold aDiscountStrategyfield without caring which specific implementation it is.
Exercise
This class violates the Single Responsibility Principle. As a comment, name the two separate responsibilities it's mixing together.
Show hint
Look for two unrelated reasons this class might need to change.
SOLID Principles in Apex Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
SOLID is five related principles for designing maintainable object-oriented code — several of them are things Module 11's OOP tools (interfaces, polymorphism) already make possible.