Apex Design Patterns
What Are Design Patterns in Apex?
Short Description
Design patterns are proven ways to organize code so it’s easier to read, test, and scale as applications grow.
Simple Explanation
Design patterns are like architectural blueprints—they tell you where everything should go.
Gist (Quick Revision)
Design patterns keep Apex clean, reusable, and easy to maintain.
1. MVC (Model–View–Controller)
What Is MVC?
MVC separates responsibilities into three parts:
-
Model → Data & business logic
-
View → UI (Lightning, Visualforce)
-
Controller → Handles user actions
Real-Life Example
Ordering food at a restaurant:
-
Menu & kitchen rules → Model
-
Menu card → View
-
Waiter → Controller
Apex MVC Example
// Controller
public with sharing class AccountController {
public static List<Account> getAccounts() {
return AccountService.getAccounts();
}
}
// Service (Model logic)
public class AccountService {
public static List<Account> getAccounts() {
return [SELECT Id, Name FROM Account LIMIT 10];
}
}
Why MVC Matters
-
Cleaner UI code
-
Easier testing
-
Better separation of concerns
Gist (Quick Revision)
MVC separates UI, logic, and data for cleaner architecture.
2. Service Layer Pattern
What Is the Service Layer?
The Service Layer contains business logic, separate from UI and triggers.
Simple Explanation
Service layer is the brain of your application.
Real-Life Example
Rules like “Gold customers get 20% discount” belong in the service layer—not in triggers or UI.
Service Layer Example
public class DiscountService {
public static Decimal calculateDiscount(Decimal amount) {
return amount * 0.20;
}
}
Benefits
-
Reusable logic
-
Easier testing
-
No duplicated code
Gist (Quick Revision)
Business logic belongs in service classes, not triggers or controllers.
3. Selector & Repository Patterns
What Is the Selector Pattern?
Selectors handle SOQL queries only.
Simple Explanation
Selector = data reader.
Selector Example
public class AccountSelector {
public static List<Account> selectByIndustry(String industry) {
return [SELECT Id, Name FROM Account WHERE Industry = :industry];
}
}
What Is the Repository Pattern?
Repositories handle DML operations (insert, update, delete).
Simple Explanation
Repository = data writer.
Repository Example
public class AccountRepository {
public static void save(List<Account> accounts) {
insert accounts;
}
}
Why Use Selector & Repository?
-
Centralized queries and DML
-
Easier performance tuning
-
Cleaner service logic
Gist (Quick Revision)
Selectors read data; repositories write data.
4. Unit of Work Pattern
What Is Unit of Work?
Unit of Work manages multiple DML operations as one logical transaction.
Simple Explanation
Like submitting all changes at once instead of saving one by one.
Real-Life Example
Updating:
-
Account
-
Contact
-
Opportunity
All succeed or fail together.
