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

Apex Execution and Separation of Concerns

When starting to write Apex, it is tempting to start with an Apex Trigger or Apex Controller class and to start placing the required logic in those classes to implement the desired functionality. This chapter will explore a different starting point; one that allows the developer to focus on writing application business logic (the core logic of your application) in a way that is independent of the calling context. It will also explain the benefits that it brings in terms of reuse, code maintainability, and flexibility, especially when applying code to different areas of the platform.

We will explore the ways in which Apex code can be invoked, the requirements and benefits of those contexts, their commonalities, their differences, and the best practices that are shared. We will distill these into a layered way of writing code that teaches...

Execution contexts

An execution context on the platform has a beginning and an end; it starts with a user or system action or event, such as a button click or part of a scheduled background job, and is typically short-lived, with seconds or minutes instead of hours before it ends. It is especially important in multitenant architecture because each context receives its own set of limits around queries, database operations, logs, and the duration of the execution.

In the case of background jobs (Batch Apex), instead of having one execution context for the whole job, the platform splits the information being processed and hands it back through several execution contexts in a serial fashion. For example, if a job was asked by the user to process 1,000 records and the batch size (or scope size in Batch Apex terms) was 200 (which is the default), this would result in five distinct execution...

Apex governors and namespaces

Platform governors prevent any one execution context from consuming excessive resources on the service, which could be detrimental to its users. Overall, an execution context cannot exceed 10 minutes, though within an execution context, in practice, other limits would likely be reached before this.

For example, Apex code units executing within an execution context can only collectively execute for a maximum of 10 or 60 seconds depending on the context. Over the years, Salesforce has worked hard to consolidate what was once a confusing array of governors, which also varied based on a number of Apex code contexts. Thankfully, these days, governors are much easier to follow, and vary only based on the context, being interactive or batch (asynchronous).

...

Where is Apex used?

The following table lists the types of execution contexts that Apex code can be run from and considerations with respect to security and state management. While a description of how to implement each of these is outside the scope of this book, some aspects, such as Batch Apex, are discussed in more detail in a later chapter when considering data volumes:

Execution context

User

Security

State management

Anonymous Apex

Current user

 

Sharing is enforced by default, unless disabled by applying the without sharing keyword to the enclosing class.

CRUD and FLS are enforced by default, but only against the code entered directly into the Execute Anonymous window. The code will fail to compile if the user does not have access to the objects or fields referenced.

Note that checking is only performed by the platform at compilation time; if the...

Separation of concerns

As you can see, there are a number of places Apex code is invoked by various platform features. Such places represent areas for valuable code to potentially hide. It is hidden because it is typically not easy or appropriate to reuse such logic as each of the areas mentioned in the previous table has its own subtle concerns with respect to security, state management, transactions, and other aspects such as error handling (for example, catching and communicating errors) as well as varying needs for bulkification.

Throughout the rest of this chapter, we will review these requirements and distill them into SOC that allows a demarcation of responsibilities between the Apex code used to integrate with these platform features versus the code implementing your application business logic, such that the code can be shared between platform features today and in the...

Patterns of Enterprise Application Architecture

So far, we have only discussed SOC between the Apex code invoked from an execution context (Apex Controller, Scheduler, Batch Apex, and so on) and reusable application business logic code placed in the Service classes. However, there are further levels of granularity and patterns that help focus and encapsulate application logic further, known as Enterprise Application Architecture patterns.

The general definitions of the patterns used in the next three chapters of this book are not inherently new, but are a new implementation for this platform. They have been and continue to be incredibly popular on other platforms. The original author of these patterns is Martin Fowler, who describes the other patterns in his book, Patterns of Enterprise Application Architecture (http://www.martinfowler.com/books/eaa.html).

This book takes some...

Unit testing versus system testing

When it comes to testing the Apex code, we know the drill: write good tests to cover your code, assert its behavior, and obtain at least 75 percent coverage. Force.com will not allow you to upload packaged code unless you obtain this amount or higher. You also have to cover your Apex Trigger code, even if it's only a single line, as you will soon see is the case with the implementation of the Apex Triggers in this book.

However, when it comes to unit testing, what Force.com currently lacks, however, is a mocking framework to permit more focused and isolated testing of the layers, mentioned in the previous sections, without having to set up all the records needed to execute the code you want to test. This starts to make your Apex tests feel more like system-level tests, having to execute the full functional stack each time.

While conventions...

Packaging the code

The source code provided with this chapter contains skeleton Apex classes shown in the UML diagrams used earlier in the chapter. In the upcoming chapters, we will flesh out the methods and logic in them. The following is a list of the Apex classes added in this chapter and the application architecture layer they apply to:

Apex class

Layer

SeasonController.cls

Visualforce Controller

SeasonControllerTest.cls

Apex test

ContestantController.cls

Visualforce Controller

ContestantControllerTest.cls

Apex test

RaceController.cls

Visualforce Controller

RaceControllerTest.cls

Apex test

SeasonNewsletterScheduler.cls

Apex Scheduler

SeasonNewsletterSchedulerTest.cls

Apex test

RaceService.cls

Race Service

RaceServiceTest.cls

Apex test

SeasonService.cls

Season Service

SeasonServiceTest.cls

Apex test...

Summary

In this chapter, we have taken an in-depth look at how the platform executes Apex code and the different contexts from which it does so. We have also taken the time to understand how key concepts such as state and security are managed, in addition to highlighting some Apex governors and their respective scopes.

This has enabled us to identify some common needs, and using the principles of separation of concerns we can develop guidelines to be applied to layers in our business application code, making the Apex logic more reusable and accessible from different contexts as your application functionality and, indeed, the platform itself evolve.

As we progress further into practicing SOC, the Domain, Service, and Selector layer patterns will become a further layer of separation within our application business logic. We will continue to define the naming and coding guidelines...

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