Reader small image

You're reading from  Salesforce Lightning Platform Enterprise Architecture - Third Edition

Product typeBook
Published inNov 2019
Reading LevelIntermediate
PublisherPackt
ISBN-139781789956719
Edition3rd Edition
Languages
Concepts
Right arrow
Author (1)
Andrew Fawcett
Andrew Fawcett
author image
Andrew Fawcett

Andrew Fawcett has over 30 years of experience holding several software development-related roles with a focus around enterprise-level product architecture. He is experienced in managing all aspects of the software development life cycle across various technology platforms, frameworks, industry design patterns, and methodologies. He is currently a VP, Product Management, and a Salesforce Certified Platform Developer II at Salesforce. He is responsible for several key platform features and emergent products for Salesforce. He is an avid blogger, open source contributor and project owner, and an experienced speaker. He loves watching movies, Formula 1 motor racing, and building Lego!
Read more about Andrew Fawcett

Right arrow

Application Selector Layer

Apex is a very expressive language that is used to perform calculations and transformations of data entered by the user or records read from your Custom Objects. However, SOQL also holds within it a great deal of expressiveness to select, filter, and aggregate information without having to resort to Apex. SOQL is also a powerful way to traverse relationships (up to five levels) in one statement, which would otherwise leave developers in other platforms performing several queries.

Quite often, the same or similar SOQL statements are required in different execution contexts and business logic scenarios throughout an application. Performing these queries inline, as and when needed, can rapidly become a maintenance problem as you extend and adapt your object schema, fields, and relationships.

This chapter introduces a new type of Apex class, the Selector...

Introducing the Selector layer pattern

The following is Martin Fowler's definition of the Data Mapper layer on which the Selector layer pattern is based (http://martinfowler.com/eaaCatalog/dataMapper.html):

"A layer of Mappers (473) that moves data between objects and a database while keeping them independent of each other and the Mapper itself."

In Martin's definition, he is referring to objects as those resulting from the instantiation of classes within an OO language such as Java or Apex. Of course, in the Force.com world, this has a slightly ambiguous meaning, but is more commonly thought of as the Standard or Custom Object holding the record data.

One of the great features of the Apex language is that it automatically injects object types in the language that mirror the definition of the Custom Objects you define. These so-called SObjects create a...

Implementing design guidelines

The methods in the Selector classes encapsulate common SOQL queries made by the application, such as selectById, as well as more business-related methods, such as selectByTeam. This helps the developers who consume the Selector classes to identify the correct methods to use for the business requirement and avoids replication of SOQL queries throughout the application.

Each method also has some standard characteristics, such as the SObject fields selected by the queries executed, regardless of the method called. The overall aim is to allow the caller to focus on the record data returned and not how it was read from the database.

Sharing conventions

As stated in the previous chapter, it is good...

The Selector class template

A Selector class, like the Domain class, utilizes inheritance to gain some standard functionality. In this case, the base class, delivered through the FinancialForce.com Enterprise Apex Patterns library, fflib_SObjectSelector, is used to reduce the coding overhead in performing queries, adding some standard behaviors, and supporting best practices. These will be discussed in further detail throughout this chapter.

A basic example of a Selector class for querying Races is as follows:

public inherited sharing class RacesSelector 
extends fflib_SObjectSelector { public List<Schema.SObjectField> getSObjectFieldList() { return new List<Schema.SObjectField> { Race__c.Id, Race__c.Name, Race__c.Status__c, Race__c.Season__c, Race__c.FastestLapBy__c, Race__c...

Implementing the standard query logic

The previous Selector usage example required a cast of the list to be returned to a list of Race__c objects, which is not ideal. To improve this, you can easily add a new method to the class to provide a more specific version of the base class method, as follows:

public List<Race__c> selectById(Set<Id>raceIds){ 
  return (List<Race__c>) selectSObjectsById(raceIds); 
}

Therefore, the usage code now looks like this:

List<Race__c> races =  
  new RacesSelector().selectById(raceIds);  

By using a selector for querying races, the preceding code is much smaller and therefore easier to read by other developers. In the next section, we will discover what other standard features are provided by the fflib_SObjectSelector class.

...

Implementing the custom query logic

Take a look at the implementation of the selectSObjectById base class method we have been using so far in this chapter. The following buildQuerySObjectById method code gives us an indication of how we implement custom Selector methods; it also highlights the newQueryFactory base class method usage:

public List<SObject> selectSObjectsById(Set<Id>idSet) { 
  return Database.query(buildQuerySObjectById()); 
} 
private String buildQuerySObjectById() { 
  return newQueryFactory(). 
           setCondition('id in :idSet'). 
           toSOQL(); 
} 

The newQueryFactory method exposes an alternative object-orientated way to express a SOQL query. It follows the fluent design model with its methods, making code less verbose. For more information on this approach, see https://en.wikipedia.org/wiki/Fluent_interface.

The instance...

Introducing the Selector factory

Chapter 6, Application Domain Layer, introduced the concept of a Domain factory, which was used to dynamically construct Domain class instances implementing a common Apex Interface in order to implement the compliance framework.

The following code is used in the ComplianceService.verify method's implementation, making no reference at all to a Selector class to query the records needed to construct the applicable Domain class:

fflib_SObjectDomain domain = 
  Application.Domain.newInstance(recordIds); 

So, how did the Domain factory retrieve the records in order to pass them to the underlying Domain class constructor? The answer is that it internally used another factory implementation called the Selector factory.

As with the Domain factory, the Selector factory resides within the Application class as a static instance, exposed via the...

Updating the FormulaForce package

Review the updated code supplied with this chapter and create a new package version so that you can test out the upgrade process of your package if desired. During the installation of the new package version, you should observe that the new Field Set component added in this chapter is shown as one of the new components included in the upgrade.

Summary

Through the Selector pattern covered in this chapter, you have learned about a powerful layer of encapsulation that is used for some critical logic in your application. This enforces the best practices surrounding security and provides a more consistent and reliable basis for code dealing with the SObject data.

You also learned that Selectors can also assume the responsibility and concern for platform features such as Multi-Currency and Field Sets. Ultimately, allowing the caller – be that the Service, Domain, Apex Controllers, or Batch Apex—to focus on their responsibilities and concerns leads to cleaner code that is easier to maintain and evolve.

With the introduction of the Selector factory, we discovered some common features provided by this layer in the form of the Application.Selector.selectById and Application.Selector.newInstance methods...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Salesforce Lightning Platform Enterprise Architecture - Third Edition
Published in: Nov 2019Publisher: PacktISBN-13: 9781789956719
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Andrew Fawcett

Andrew Fawcett has over 30 years of experience holding several software development-related roles with a focus around enterprise-level product architecture. He is experienced in managing all aspects of the software development life cycle across various technology platforms, frameworks, industry design patterns, and methodologies. He is currently a VP, Product Management, and a Salesforce Certified Platform Developer II at Salesforce. He is responsible for several key platform features and emergent products for Salesforce. He is an avid blogger, open source contributor and project owner, and an experienced speaker. He loves watching movies, Formula 1 motor racing, and building Lego!
Read more about Andrew Fawcett