Learning Salesforce Development with Apex
eBook - ePub

Learning Salesforce Development with Apex

Write, Run and Deploy Apex Code with Ease

Paul Battisson

Share book
  1. English
  2. ePUB (mobile friendly)
  3. Available on iOS & Android
eBook - ePub

Learning Salesforce Development with Apex

Write, Run and Deploy Apex Code with Ease

Paul Battisson

Book details
Book preview
Table of contents
Citations

About This Book

Learn to harness the power of the Apex language to build Salesforce applications Key Features

  • Learn how to work with the Apex language
  • Learn how to develop Apex Triggers
  • Learn how to use SOQL and SOSL to retrieve data
  • Learn how to write Object-Oriented Salesforce code
  • Explore the best practices to deliver scalable and maintainable code

  • Description
    This book covers the fundamentals of the Salesforce Apex programming language used by developers to build powerful applications in the cloud.
    In this book, you will learn how to work with the Apex language to build scalable applications that can interact with and update data from your users. We cover the language from the ground up, introducing programming concepts such as variables and control statements alongside clear and concise examples to help you understand the key concepts and features. Platform-specific features such as Apex triggers, SOQL and SOSL are covered in detail to help ensure you deliver robust and scalable solutions. Nuances and best practices for development are discussed along with how to effectively test your code to ensure that you can deploy it to users with confidence. Object-oriented programming in Apex is also covered in-depth to ensure that you can develop dynamic solutions and build for the future. The book also discusses and shows developers how to integrate with third-party solutions using REST APIs in Apex. By the end of the book, the reader will know how to start developing applications using Apex with confidence. What will you learn
  • Learn how to declare variables in Apex.
  • Understand how to work with collections in Apex.
  • Use different control statements within Apex to control program flow.
  • Learn how to use the built-in tools to test in Apex.
  • Understand how to make callouts to external applications and data sources.

  • Who this book is for
    This book is intended for those starting out with Apex, whether existing Salesforce Admins or those joining the Salesforce ecosystem with little professional prior programming experience, such as students. The reader is expected to have some basic familiarity with Salesforce as a platform, although key concepts are reviewed. Table of Contents
    0. Introduction
    1. An Introduction to the Salesforce Platform
    2. What is Apex?
    3. Variables in Apex
    4. Collections
    5. Control Statements
    6. Apex Triggers
    7. SOQL
    8. SOSL
    9. Defining Apex Classes
    10. Apex Class Inheritance
    11. Testing Apex
    12. Callouts in Apex
    13. Epilogue About the Author
    Paul Battisson is a 7x Salesforce MVP, holds numerous Salesforce certifications, is a Salesforce Certified Instructor and co-leader of the Leeds Salesforce Developer Group. He runs the CloudBites.TV website and YouTube channel, which has over 108k views of free training content for Salesforce admins, developers and architects. He is the COO of Cloud Galacticos, a UK based Salesforce consulting partner. Your Blog links:
    www.paulbattisson.com
    www.cloudbites.tv Your LinkedIn Profile:
    https://www.linkedin.com/in/paulbattisson/

Frequently asked questions

How do I cancel my subscription?
Simply head over to the account section in settings and click on “Cancel Subscription” - it’s as simple as that. After you cancel, your membership will stay active for the remainder of the time you’ve paid for. Learn more here.
Can/how do I download books?
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
What is the difference between the pricing plans?
Both plans give you full access to the library and all of Perlego’s features. The only differences are the price and subscription period: With the annual plan you’ll save around 30% compared to 12 months on the monthly plan.
What is Perlego?
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Do you support text-to-speech?
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Is Learning Salesforce Development with Apex an online PDF/ePUB?
Yes, you can access Learning Salesforce Development with Apex by Paul Battisson in PDF and/or ePUB format, as well as other popular books in Informatique & Programmation Web. We have over one million books available in our catalogue for you to explore.

Information

Year
2020
ISBN
9789389898187

CHAPTER 1

An Introduction to the Salesforce Platform

Let’s begin with an introduction to Salesforce and the Salesforce Platform. It is likely that you will have at least some familiarity with Salesforce and the Salesforce Platform (often called Force.com), but as this book may be read by a variety of audiences I think it best we cover some base material together. If you have been working with Salesforce for a number of years then you may be able to skip this chapter, but I encourage you to read it as a refresher if nothing else.

Structure

In this chapter we will cover:
  • What a multi-tenant cloud is and what multi-tenancy means
  • How the Salesforce database is structured
  • What are objects and fields
  • The declarative tools available to a Salesforce developer

Objectives

By the end of this chapter you should:
  • Understand what multi-tenancy is and the impact multi-tenancy has on programming
  • How the Salesforce database is structured
  • What are objects and fields?
  • What declarative tools are available to us as Salesforce developers which we can utilize?

The birth of the cloud

In 1999, at the height of the dot com bubble, Salesforce was born and with it cloud computing. Salesforce was the leader of a new wave of companies that would come to dominate the industry by switching the way in which software was distributed and paid for on its head.
Software as a Service (SaaS) was a new way of paying for software whereby you simply paid a monthly fee for each user and the vendor dealt with everything else. No hardware, no installations, regular updates, all dealt with for you. Whereas now this seems commonplace, 20 years ago it was revolutionary.
In order to deliver software in this way, a new computing model was needed and thus the cloud was born. Salesforce, unlike its competition, would not require you to have a server somewhere, they would run the solution for you. But with this new model came the challenge of actually building a solution that could scale in a repeatable and simple fashion, that did not need migration to bigger servers constantly, and that would democratize the underlying resources to allow this scaling.

Multi-tenancy

Salesforce is different from many other clouds in that it is multi-tenant, that is customers share resources. When cloud computing was first popularized, it was mainly about moving a server out from your office or building, and into another building - you were still paying for the same underlying server hardware somewhere. With multi-tenancy, this was all abstracted away so you didn’t have to worry about it.
I like to think of it as renting an apartment instead of buying a house. In an apartment building, there are shared services such as water, electricity, and heating. Each tenant in the building gets access to the same amount of each of these and they don’t worry about the underlying pipes and management. This is nice and scalable as almost all apartments follow a standard layout and if anything goes wrong, the landlord deals with it. With a house, you may have access to a greater amount of control for how much heat you get, who supplies everything, and some of the core features of the property, but if something goes wrong, you also have to pay to fix it all. You are in control of everything, including security and maintenance. Now for a house, this may be simple enough and manageable, but for a large scale IT infrastructure, this is not as easy.
Figure 1.1: Multi vs. single tenancy
With our apartment, if you need more space, you simply get more space by renting out a bigger apartment. If the landlord upgrades the internet connectivity to the apartment building, everyone gets faster internet.
Whilst multi-tenancy may seem a no-brainier when laid out here, there are some limitations, and on Salesforce these take the form of governor limits. Because the resources are shared, we have to have some rules in place to ensure that one organization does not slow down all of the others. We will discuss this in a lot more detail in the next chapter.

The Salesforce database

One of the common questions that follow from the idea of multi-tenancy is does my data live inline with data from other companies?
The simple answer to this is no. The way in which Salesforce structures the underlying database is one of the many very clever things about Salesforce, and is important for us to understand when we think about how we are writing code, and how our data is both stored and retrieved.
Firstly, each Salesforce organization, or tenant, has a unique OrgID. You can find yours in the Company Information section of the Setup menu. This unique identifier is used by Salesforce to physically partition the underlying data to both assist in performance but also for querying and scalability. Whenever a query is run in Salesforce, the query engine is targeting a specific tenant’s information and so only data within a particular partition is considered.
Figure 1.2: Finding your Organization ID
The database itself is just a small number of tables that are used to store the metadata for the environment and the data that is being stored. Metadata is data about data, and is used by Salesforce to record the entire structure of our environment. This is one of the reasons that when we create a new object or field in Salesforce that we can quickly add it to the page layout or migrate it between systems, it is simply metadata. Those who have worked with other database solutions know that creating and migrating data structures is a more complex and involved task than it often seems with Salesforce.

Objects and fields

Now that we understand that Salesforce is not creating tables for us under the hood, we get an insight into why Salesforce has objects and fields instead of tables and columns. Objects and fields in Salesforce are analogous to tables and columns in other databases but importantly are not created as separate tables in the underlying database.
Again, we will see later on how this becomes more important, but for now, we simply need to know that objects in Salesforce are like tables in other database systems and are the entities about which we are storing data, for example, accounts and contacts. Each object in Salesforce has a label such as Job and an API name or developer name. For standard objects, which are those created and maintained by Salesforce, this is simply the same as the label, without spaces, for example, Account, Contact, OpportunityProduct, and FeedPost. For custom objects that we define, the __c suffix is added to denote it is custom, for example, Job__c. The same naming convention is also in place for fields, with standard fields such as Name and LastModifiedDate, and custom field Job_Title__c. Whenever we access an object or field in Apex we need to make sure we use the correct API name.

Permissions and sharing

Salesforce controls access to data through two mechanisms, permissions, and sharing. Permissions are focussed on what you can do with different objects and follow the standardized CRUD (Create-Read-Update-Delete), model. Permissions are assigned through either a profile or a permission set. Sharing focusses on what records you can see and use these permissions upon. This is a combination of the org-wide default for the object, any inherited sharing through relationships, roles, groups and territories, and then sharing rules and manual sharing.
The reason I bring this up is that Apex runs in system context and will not automatically enforce permissions. This can be extremely useful for us when we want to perform an action that we do not want our users to be able to do on their own, however, care should be taken in certain contexts to ensure that permissions are enforced appropriately. Similarly, Apex can be told to enforce or ignore sharing for a particular user, so when developing our applications we will need to be aware of any inbuilt assumptions we have around whether users should or should not be able to see and or do particular things.

From clicks to code

We’ve mentioned a number of declarative features already for Salesforce, and it is outside the scope of this book to cover them all completely, but we should touch on the principle of using clicks and not code within Salesforce whenever reasonable.
One the past few years Salesforce has improved immensely in terms of the power of its declarative automation tools, namely Flow and Process Builder. These tools have enabled administrators and developers to automate much more rapidly in a way that is easier to maintain. However, these tools are not a panacea, and consideration should always be taken as to when to move from clicks to code.
Code will, in general, always be faster at running a task than an equivalent declarative tool if coded appropriately. For many situations, the performance is so close as to make this difference negligible. However, as volumes grow and complexity increases, the differences become more noticeable and require more thought. As both scale and complexity increase together, code will more than likely become the better choice and make a solution more maintainable.
There are a number of best practices around how to implement and manage your use of declarative tools to help increase a solution’s maintainability, scalability, and reliability. Utilizing these practices can help you to move the requirement for code further down the road, but it is unlikely to ever eliminate it completely. Let’s look briefly at some declarative tools and when they are unable to be used.

Workflow Rules

Workflow rules are an extremely powerful engine for you to be able to manage small updates to a record on save. You can also create email alerts, tasks, and send outbound messages. These all operate on a per-record basis and are limited to only being able to update the record in context or records it has a relationship to via lookup or as a detail in amaster-detail relationship. It also has the ability to set certain actions to occur at a specified time. However, you cannot manage records that are not related or child records, and so must use either Process Builder, Flow, or an Apex trigger.

Process Builder

Process Builder is an abstraction of the Flow automation tool which we will discuss in below, and provides a way for you to define a very specific set of instructions to be reviewed and acted upon in order. Process Builder allows you to update related records in both directions within a record’s hierarchy and like workflow, define time-dependent actions. The primary limitations for Process Builder are around bulkification and order of execution.
A best practice is to ensure that for a single object that there is a single Process Builder process defined with all control managed through this one process. In practice, this is not always maintainable and may require the process to be migrated to an Apex trigger. If you find yourself in a situation where you require more than one process per object you should consider migrating these processes to Apex. Process Builder processes have no guaranteed order of execution and so can lead to chained or unexpected results occurring.

Flow

Flow is a powerful drag and drop programming tool from Salesforce that enables you to draw flow diagrams that Salesforce then interprets into code to run. You can define variables, logic, and loops that enable you to do a lot of simple trigger tasks in a declarative fashion by combining it with Process Builder. You can also create screen flows that define simple to use wizard-style user interfaces.
I am a big fan of Flow for its simplicity and the amount you can do within it. However, performance, bulkification, and manageability are the key areas of concern that will make you think of using Apex code. In many situations, Apex will be more performant than Flow as a developer has hand written code tailored to the desired task – although this is not always true. Flow can be more difficult to modularise and maintain at scale, and as complexity increases. A team will have to think and agree upon a common way of mudlarising and structuring their Flows, something that is a well-solved problem in programming. This also has implications upon the bulkification of data processing, something we will cover in detail in this book for Apex.

Choose the right tool at the right time

I have listed the declarative tools above in a particular order to illustrate how I view the spectrum of Salesforce automation, as shown below. On the far left, you have the purely declarative and restricted solutions such as formulas, validation rul...

Table of contents