(Ebook) Advanced Apex Programming in Salesforce by Dan Appleman ISBN 9781936754120, 1936754126 2024 scribd download
(Ebook) Advanced Apex Programming in Salesforce by Dan Appleman ISBN 9781936754120, 1936754126 2024 scribd download
com
https://ebooknice.com/product/advanced-apex-programming-in-
salesforce-23495170
DOWLOAD EBOOK
https://ebooknice.com/product/advanced-apex-programming-in-
salesforce-34774506
ebooknice.com
ebooknice.com
ebooknice.com
(Ebook) Biota Grow 2C gather 2C cook by Loucas, Jason;
Viles, James ISBN 9781459699816, 9781743365571,
9781925268492, 1459699815, 1743365578, 1925268497
https://ebooknice.com/product/biota-grow-2c-gather-2c-cook-6661374
ebooknice.com
https://ebooknice.com/product/the-apex-shifter-complete-set-apex-
shifter-1-3-29856600
ebooknice.com
ebooknice.com
ebooknice.com
ebooknice.com
Advanced Apex Programming in Salesforce
Fourth Edition
By
Dan Appleman
Desaware Publishing
ISBN: 978-1-936754-13-7
www.AdvancedApex.com
Table of Contents
Introduction
Sample Code
2 – Static Variables
3 – Limits
4 – Bulk Patterns
6 – Triggers
7 – Going Asynchronous
8 – Concurrency
9 – Application Configuration
11 – Unit Tests
12 – Designing for Packages
13 - Maintaining Apex
Conclusion
Acknowledgements
I just wanted to get that out of the way. I know there is sometimes
value in the kind of book where 90% of the content is a rephrasing
of the documentation and only 10% is new and interesting – a good
author can organize information to make it easier for beginners to
learn. But they are frustrating for intermediate and advanced
developers who have to sift endlessly through familiar content to
find one or two nuggets of new material.
So I’m going to assume that you either have read, or can read, the
Salesforce Apex language documentation. If you are new to Apex,
you will find this book helpful – especially if you are coming to Apex
from another language, but it is not a tutorial and will not replace
the Apex documentation. If you have Apex programming experience,
I’m confident you’ll find material here that will at the very least
prove thought provoking, if not occasionally mind-blowing.
About eight years ago, I joined her and two others to establish a
new company, Full Circle Insights, to develop a new Salesforce
application related to marketing and sales data and analytics. As
CTO, I designed and built the application – which evolved into a very
large and sophisticated native AppExchange app (an app that runs
entirely on the Force.com platform). In doing so, I learned a lot.
By the time you’re done, I think you will find it was well worth the
effort.
Dan Appleman
[email protected]
Note to Readers of Previous
Editions
The Salesforce platform is updated three times a year. Some of the
updates are minor, some more significant, and some lead to radical
changes in what most would consider to be “best practices”. Best
practices are tricky – you can’t assume that just because something
is new, it represents the best way to do something.
Not only has the platform changed, but my own experience has
changed – or put another way, I keep learning as well. And since
this is a book born of real-world experience, those new experiences
are reflected in each new edition, along with those new platform
features that seem truly useful.
Instead, when you download the sample code you’ll see it includes a
git repository. Each chapter has a branch in Salesforce DX format
that you can check out when learning that particular chapter. Some
chapters include multiple commits to mark different steps or
variations of the code illustrated in the chapter.
The sample code for some chapters includes a permission set named
“Advanced Apex” which you can assign to the current user to quickly
obtain access to fields or other elements used by the examples. In
other cases, you may need to explicitly set field or tab permissions.
For those who are not familiar with git, I recommend using
Sourcetree (https://www.sourcetreeapp.com), which is an excellent
GUI on top of git.
You will need to install the sample code to follow some of the
content in this book – the book does not contain the complete
listings of all the sample code.
About the Code Listings
This edition of Advanced Apex programming uses HTML formatted
text for listings. This is supported on all newer e-reader devices, but
will result in a poor experience on older devices that do not support
a mono-spaced font.
Depending on your device, you may see code listings wrap in ways
that make them hard to read. In those cases you'll find that it is
much easier to read the listings if you place your device in landscape
mode (supported on all newer devices).
At the same time, it’s a useful question for exactly that reason.
Because you do know what a computer language is, you’ll probably
be grateful if I don’t waste your time answering that question. In
fact, it brings to mind a long list of questions and introductory
material that are not worth discussing at all, either because you
should know them, or because you can easily find them in the
documentation.
So let’s begin with a partial list of material that I won’t try to teach
you.
Beyond Syntax
When we talk about computer languages in the context of actual
software development, we’re really talking about three different
things:
Of these, this book will almost completely ignore the first item. If
you’ve used Apex at all, you’re probably well familiar with its syntax.
If you are migrating from another language, suffice to say that Apex
is syntactically similar to Java or C#, with most of the constructs you
would expect from a modern object-oriented language, including
support for single inheritance and interfaces.
Most of this book will be dealing with the third item on the list – the
interaction of the language with the platform. But the rest of this
part of the book will focus on the four key concepts that you must
understand in order to succeed in Apex programming:
Execution Contexts
Static Variables
Bulk Patterns
Limits
I’ll be discussing both static variables and limits in more depth later.
For now, the key facts to remember (and I assure you, once you
start working in Apex, you will never forget them) are:
As you can see, both triggers run in the same execution context. So
they share the same set of limits (as long as they are in the same
application – more on that later), and the same set of static
variables.
As you can see, the field update workflow not only runs in the same
execution context, it can cause the triggers to execute again within
the same context.
At this point, if you are coming to Apex from another language, you
might be feeling a certain amount of shock. On other platforms, you,
the developer, are largely in control of your application. User input
may be unpredictable and have to be accounted for, but you know
how to do that. It’s not as if users can modify the underlying
behavior of the application, or add code that interacts with your
application. Even if you do have a plug-in model or API, those using
it will be (hopefully) knowledgeable and expected to follow your
specifications, guidelines and documentation.
But don’t let this thought scare you. You’ll quickly adjust to the idea
that your finely crafted code can be broken by a junior system
administrator writing a careless validation rule. It’s just part of the
territory – and part of what makes Apex coding a fun challenge.
That’s the case with Java, C#, C++, VB .NET and virtually every
block structured language.
You can only make up to fifty future calls from an execution context,
and you can’t make a future call from a future context. Because your
code may share an execution context with other code, ideally you
only want to invoke your future call once.
But how do you use it? You can’t use it as a flag to indicate that a
future call is required. That’s because in Apex you have no way of
knowing that you are exiting an execution context. You can,
however, use it as a flag to indicate that the call has already been
made.
@future
private static void actualFutureCall()
{
// Actual async code here
system.debug('actualFutureCall async operation');
}
}
Consider the case where you have one or more triggers or methods,
and the execution depends in some way on the user who triggered
the execution. You might be storing different field values based on
the user. Or you might be prohibiting certain operations, or
performing additional operations based on the user.
In this scenario, let’s say you’ve added a custom field to the User
object, call it UserIsSpecial__c, that controls these operations.
You can retrieve the current value of this field using the following
code:
User u = [Select UserIsSpecial__c from User
where ID = :UserInfo.getUserId()];
Boolean userIsSpecial = u.UserIsSpecial__c;
If you were only using this value in one place in your code, this
would be fine – you could just use the query as is. But if you intend
to use this value across multiple methods and triggers, this approach
could result in numerous SOQL operations (SOQL being the database
query language for the Force.com platform). The number of allowed
SOQL calls is limited within an Execution context – so you want to
minimize those calls where possible.
The solution is to cache the value the first time it is used. Rather
than try to anticipate where the first use will be (which can be tricky
in a complex application), it’s best to centralize access of the variable
by placing it in an Apex class as follows:
public class ThinkingInApex {
}
}
It turns out that taking this approach has additional benefits. What if
you later decide that you need other information from the user
record? Say, the current user’s time zone?
Comme le droit est par lui-même une force, la force par elle-
même peut être un droit. Le genre humain et l’Église reconnaissent
un droit de la guerre. De ce fer qu’il ôtait à la force barbare, le
christianisme a fait des cuirasses pour les faibles, de nobles épées
dont il a armé le droit. La force aux mains de l’Église est la force du
droit, et nous ne voulons pas que le droit demeure sans force. La
force à sa place et faisant son office, voilà l’état régulier.
Parce que dans le monde présent la force n’est pas partout à sa
place, c’est-à-dire à la disposition de l’Église ; parce que loin de
servir le droit, elle abuse contre le droit, conclurons-nous avec les
illuminés qui décrètent, les uns l’anéantissement de la force, les
autres que le droit suprême n’aura plus jamais la force en main, de
peur qu’il ne vienne à gêner la liberté qui veut détruire la vérité ?
Il faudrait, au contraire, donner avec joie tout autre sang pour
remettre la force dans son rôle légitime, pour l’attacker au seul
service du droit.
La force doit protéger, affermir, venger le plus grand, le plus
illustre, le plus nécessaire droit de l’homme, qui est de connaître et
de servir Dieu ; elle doit mettre l’Église à même de dispenser ce droit
à tout homme sur la terre. N’abandonnons pas cette vérité que le
catholicisme libéral jette et noie dans le courant, avec tant d’autres.
XIX
On est attristé de voir des hommes d’un grand mérite et qui ont
rendu de grands services, s’efforcer de faire pénétrer chez les
catholiques des doctrines que ceux-ci repoussent comme
attentatoires aux droits et à la dignité de l’Église, tandis que les
adversaires et les ennemis de l’Église les rejettent comme encore
trop imprégnées de l’esprit chrétien. Leurs formules, inspirées par
cet esprit de compromis qui confond toutes les limites, rencontrent
partout le même sort malheureux. Ils parlent de l’indépendance de
l’Église : ce mot seul est de trop pour les révolutionnaires, on leur
enjoint de l’effacer : et en même temps, d’un autre côté, comme ils
parlent aussi de l’indépendance de l’État, les catholiques observent
que sous le couvert de ce mot, par la force des choses, ils
subordonnent la société religieuse au pouvoir civil et font dépendre
l’existence matérielle du christianisme de la bienveillance de ses
ennemis, lesquels, en toute circonstance, se montrent non-
seulement indifférents mais hostiles, non-seulement hostiles mais
furieux. Il s’agit toujours de concilier l’inconciliable, d’obtenir pour
l’Église une grâce qu’on ne veut point lui accorder, de soumettre
l’Église à des conditions de grâce qu’elle ne saurait supporter. Nulle
richesse d’éloquence ne peut dissimuler longtemps ce fond
d’incurable misère, nulles paroles dans aucune langue n’ont une
élasticité qui puisse mettre d’accord et retenir ensemble de pareilles
contradictions. Libre coopération, indépendance réciproque des
deux pouvoirs, etc. Que signifient ces sonorités ? Que tirer
pratiquement de la « libre coopération » de l’âme et du corps, de
« l’indépendance réciproque » de la matière et de l’esprit ?
Il y a des mots plus malheureux, parce qu’ils ont une portée plus
nette. L’invitation faite à l’Église de renoncer au privilége est un de
ces mots qui blessent le sens catholique.
En effet, l’Église a une constitution divine, elle vit de son droit
propre, et non de privilége. Qui donc lui aurait accordé un privilége
qui ne lui appartînt pas de nature ? L’État ? Mais alors la société
civile est donc supérieure à la société religieuse et peut légitimement
lui reprendre ce qu’elle lui a bénévolement octroyé ? L’histoire,
d’accord avec le bon sens chrétien, condamne la fausse vue que
trahit ce langage. L’Église n’a pas été faite par l’État : c’est elle au
contraire qui a fait l’État et la société ; et ni l’État ni la société n’ont
octroyé à l’Église des priviléges : ils lui ont reconnu une manière
d’être antérieure à leur propre existence, un droit qui ne relève d’eux
en aucune sorte et qu’ils ne peuvent modifier que par un abus contre
lequel l’intérêt public l’oblige de protester.
Nous ne pouvons partager l’ignorance où l’ingratitude
révolutionnaire prend soin de s’enfermer. Nous savons que l’Église a
grandi malgré la puissance païenne, qu’elle a changé l’assiette du
monde, qu’elle est, en un mot, la mère et l’institutrice des États
chrétiens, et que la supériorité de leur civilisation est due à ses
principes et en dépend toujours. Nous savons aussi que l’Église n’a
pu accomplir ce grand ouvrage, ne l’a pu défendre et ne le pourra
maintenir qu’au moyen de cette constitution propre qui lui a été
donnée de Dieu pour agir dans le monde en sa double qualité de
Mère et de Reine, également maîtresse du genre humain par
l’amour, par la lumière et par l’autorité. Et nous attribuerons
aujourd’hui aux écoulements déjà si restreints de cette suprématie
maternelle et royale, le caractère flétrissant de priviléges, de
concession humaine qu’il faut enfin abdiquer ! L’Église a moins
encore le droit de les abdiquer que la société le droit de les
suspendre, car il ne lui est pas donné de se méprendre sur la source
d’où ils viennent et sur le but qu’ils doivent réaliser. En présence de
l’État incrédule ou hérétique, elle saura subir la privation temporaire
de l’exercice de sa prérogative divine ; elle ne peut proclamer qu’elle
en fait l’abandon, qu’elle rejette comme mauvais ou superflu ce qui
lui a été, non-seulement conféré, mais imposé de Dieu pour le bien
du monde. Quand l’Église conclut un concordat, elle ne traite pas en
subordonnée, mais en supérieure ; c’est elle qui concède ; elle ne
reçoit pas des priviléges, elle en accorde. Elle les accorde à regret,
car si elle évite par là un plus grand mal, l’expérience a trop prouvé
que ces concessions ne sont guère propices au bien général, rien de
ce qui affaiblit le sentiment chrétien ne pouvant tourner à l’avantage
de personne.
L’argument que le Libéralisme croit tirer de ces concessions
contre les principes, est indigne d’une raison chrétienne. En premier
lieu, l’Église ne concède point sur les principes, ne signe point de
traités où ils ne soient réservés. En second lieu, exposée aux coups
emportés de la force et n’ayant d’autre arme naturelle que sa
patience, l’Église, suivant la profonde observation de J. de Maistre,
« ne refuse à la souveraineté qui s’obstine, rien de ce qui ne fait
naître que des inconvénients. »
XXV
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebooknice.com