Advanced 30 min read

Selector Layer

By the end of this lesson, you'll be able to:

  • Define what belongs in a selector class
  • Consolidate a scattered query into a single reusable selector method
  • Explain the benefit of having one place where a given query is defined

Prerequisites: "Service Layer"

The scattered version

Module 42's banking system queried Bank_Account__c in at least three separate places: the balance-update trigger, the validation trigger, and BankAccountService.getAccountsFor. Each query selected slightly different fields, and a future need to add WITH SECURITY_ENFORCED everywhere would mean editing three separate places and hoping none were missed.

Consolidating into a selector

public with sharing class BankAccountSelector {
    public List<Bank_Account__c> selectById(Set<Id> ids) {
        return [
            SELECT Id, Balance__c, Status__c
            FROM Bank_Account__c
            WHERE Id IN :ids
            WITH SECURITY_ENFORCED
        ];
    }

    public Map<Id, Bank_Account__c> selectByIdAsMap(Set<Id> ids) {
        return new Map<Id, Bank_Account__c>(selectById(ids));
    }
}

Every place that previously wrote its own Bank_Account__c query now calls BankAccountSelector.selectByIdAsMap instead — one method, one set of fields, one place where WITH SECURITY_ENFORCED (Module 28) is guaranteed to be applied consistently.

A single place a query bug can hide — or be fixed

If a bug is later found — say, Status__c should also filter out soft-deleted accounts — fixing BankAccountSelector.selectById fixes it everywhere that selector is used, instantly and consistently, rather than requiring a hunt through the codebase for every place [SELECT ... FROM Bank_Account__c] was written by hand.

Exercise

As a comment, explain why consolidating a query into one selector method is safer than three separately-written, slightly different versions of "the same" query scattered across the codebase.

Show hint

Think about what happens when the query needs to change later.

APEX

Selector Layer Quiz

1. What problem does consolidating scattered queries into a selector class solve?

Log in to submit the quiz and save your score.

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 SOQL — every query for a given object lives in one place, so a change to that query (adding a field, adding security enforcement) happens exactly once rather than being hunted down across many scattered call sites.