The Selector Layer Pattern
By the end of this lesson, you'll be able to:
- Explain what a selector class is responsible for
- Write a simple selector class method
Prerequisites: The Service Layer Pattern
Why centralize queries
Without a selector, the same-ish SOQL query — "get an Account with its key fields" — often gets rewritten slightly differently in ten different classes, each remembering (or forgetting) a different subset of fields or WHERE conditions. A selector class is the one place that knows how to fetch Accounts.
A simple selector class
Typically one method per meaningful query shape, named for what it returns rather than how (selectById, selectOpenByAccountId) — callers ask for what they need by intent, without needing to know or repeat the underlying SOQL.
A shared Account selector
public with sharing class AccountSelector {
public static List<Account> selectByIds(Set<Id> ids) {
return [
SELECT Id, Name, Industry, AnnualRevenue
FROM Account
WHERE Id IN :ids
];
}
}
Every class that needs Accounts by Id calls AccountSelector.selectByIds() instead of writing its own version of this query — one field list, one WHERE clause, used everywhere.
Exercise
Write a ContactSelector class with a method selectByAccountId(Id accountId) returning that Account's Contacts with Id, FirstName, and LastName.
Show hint
One static method, one SOQL query, returning List<Contact>.
The Selector Layer Pattern — Quick Check
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
A selector class centralizes an object's SOQL queries into one place, so every part of the codebase fetches Accounts (for example) the same consistent way, instead of similar-but-subtly-different queries scattered across dozens of classes.