Apex Enterprise Patterns Flashcards
Service Layer
Business logic - tasks, calculations and processes - for major modules/apps
Service Layer Design Considerations
Security - use ‘with sharing’ modifier, or if accessing records outside of User’s visibility - private Apex inner class ‘without sharing’.
SOC - keep validation, field values or calculations separate.
Marshalling - Leave error handling and messaging to the callers.
Make the service stateless.
Expose Services as API
Modify the class and method modifiers from ‘public’ to ‘global’.
If exposing to off-platform callers, use REST protocol.
Unit of Work in Service Code Methods
Initialize a single UOW and use it to scope all the work done by the service method.
Have the service layer logic register records w/the UOW when it executes.
Call the UOW commitWork method to bulkify and execute the DML.
Domain Layer
Object-specific default operations (triggers, validations, updates, etc. that should always execute on a database transaction).
Domain layer logic is specific to each individual object whereas services often are not.
Domain Layer use
Used by Service Layer code relating to object - via Domain classes.
Used by Apex Triggers - CRUD (and undelete) of custom objects.
Domain Layer Design Considerations
Extension by containment - While you can’t extend an sObject, you can contain it with another class that complements the data with appropriate behavioral code (methods, properties, and so on).
OOP - use inheritance to abstract common behavioral code (methods, properties, etc.) into a shared base class.
Security - use ‘with sharing’ or ‘without sharing’.
Selector Layer
Logic responsible for querying info from your custom objects and feeding it to your Domain and Service layer code.
UI Controllers and Batch Apex classes can also use them.
Selector Layer Design Considerations
Methods - static or instance scope.
Mostly returning sObject lists.
When implementing Batch Apex use a selector method to return a QueryLocator.
Can use a custom Apex class to implement a wrapper for the query result to better reflect the queried info (instead of sObject).
Security - avoid using ’with sharing’ or ‘without sharing’. If a SOQL query need to access records outside of a user’s visibility - need to elevate the execution context briefly - use a private Apex inner class w/the ‘without sharing’ modifier.
Unit of Work
Helps simplify your code when performing multiple DML statements over related objects, avoids partial db updates.
IDoWork
An Apex Interface which is a UOW extension that describes work to be performed during the commitWork method (used for ops not covered with current uow methods ie: registerDIrty, etc. are not viable).