0% found this document useful (0 votes)
687 views639 pages

Salesforce Apex Language Reference PDF

Uploaded by

satkabeer654
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
687 views639 pages

Salesforce Apex Language Reference PDF

Uploaded by

satkabeer654
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 639

salesforce: Summer '12

Force.com Apex Code Developer's Guide

Last updated: June 1 2012


Copyright 20002012 salesforce.com, inc. All rights reserved. Salesforce.com is a registered trademark of salesforce.com, inc., as are other

names and marks. Other marks appearing herein may be trademarks of their respective owners.

Table of Contents

Table of Contents
Chapter 1: Introducing Apex...............................................................................................................11
What is Apex?.........................................................................................................................................................................12
How Does Apex Work?..............................................................................................................................................13
What is the Apex Development Process?....................................................................................................................14
Using a Developer or Sandbox Organization...................................................................................................14
Learning Apex.................................................................................................................................................17
Writing Apex...................................................................................................................................................18
Writing Tests...................................................................................................................................................19
Deploying Apex to a Sandbox Organization...................................................................................................19
Deploying Apex to a Salesforce Production Organization...............................................................................20
Adding Apex Code to a Force.com AppExchange App..................................................................................20
When Should I Use Apex?..........................................................................................................................................21
What are the Limitations of Apex?.............................................................................................................................21
What's New?...........................................................................................................................................................................22
Apex Quick Start.....................................................................................................................................................................22
Documentation Typographical Conventions...............................................................................................................22
Understanding Apex Core Concepts...........................................................................................................................23
Writing Your First Apex Class and Trigger................................................................................................................28
Creating a Custom Object...............................................................................................................................28
Adding an Apex Class.....................................................................................................................................29
Adding an Apex Trigger..................................................................................................................................30
Adding a Test Class.........................................................................................................................................31
Deploying Components to Production............................................................................................................33

Chapter 2: Language Constructs.........................................................................................................35


Data Types..............................................................................................................................................................................36
Primitive Data Types...................................................................................................................................................36
sObject Types..............................................................................................................................................................39
Accessing sObject Fields..................................................................................................................................40
Accessing sObject Fields Through Relationships............................................................................................41
Validating sObjects and Fields .......................................................................................................................42
Collections...................................................................................................................................................................43
Lists.................................................................................................................................................................43
Sets..................................................................................................................................................................48
Maps................................................................................................................................................................49
Maps from SObject Arrays..............................................................................................................................50
Iterating Collections........................................................................................................................................50
Enums.........................................................................................................................................................................50
Understanding Rules of Conversion............................................................................................................................52
Variables..................................................................................................................................................................................53
Case Sensitivity............................................................................................................................................................54

Table of Contents
Constants.....................................................................................................................................................................55
Expressions..............................................................................................................................................................................55
Understanding Expressions.........................................................................................................................................55
Understanding Expression Operators..........................................................................................................................56
Understanding Operator Precedence...........................................................................................................................62
Extending sObject and List Expressions.....................................................................................................................63
Using Comments.........................................................................................................................................................63
Assignment Statements...........................................................................................................................................................63
Conditional (If-Else) Statements............................................................................................................................................65
Loops.......................................................................................................................................................................................65
Do-While Loops.........................................................................................................................................................66
While Loops................................................................................................................................................................66
For Loops....................................................................................................................................................................67
Traditional For Loops.....................................................................................................................................67
List or Set Iteration For Loops........................................................................................................................68
SOQL For Loops............................................................................................................................................68
SOQL and SOSL Queries......................................................................................................................................................70
Working with SOQL and SOSL Query Results.........................................................................................................71
Working with SOQL Aggregate Functions................................................................................................................72
Working with Very Large SOQL Queries..................................................................................................................73
Using SOQL Queries That Return One Record........................................................................................................75
Improving Performance by Not Searching on Null Values.........................................................................................75
Understanding Foreign Key and Parent-Child Relationship SOQL Queries.............................................................76
Using Apex Variables in SOQL and SOSL Queries...................................................................................................77
Querying All Records with a SOQL Statement..........................................................................................................78
Locking Statements.................................................................................................................................................................78
Locking in a SOQL For Loop....................................................................................................................................79
Avoiding Deadlocks....................................................................................................................................................79
Transaction Control................................................................................................................................................................79
Exception Statements..............................................................................................................................................................80
Throw Statements.......................................................................................................................................................80
Try-Catch-Finally Statements.....................................................................................................................................80

Chapter 3: Invoking Apex...................................................................................................................82


Triggers...................................................................................................................................................................................83
Bulk Triggers...............................................................................................................................................................84
Trigger Syntax.............................................................................................................................................................84
Trigger Context Variables...........................................................................................................................................85
Context Variable Considerations.................................................................................................................................87
Common Bulk Trigger Idioms....................................................................................................................................88
Using Maps and Sets in Bulk Triggers............................................................................................................88
Correlating Records with Query Results in Bulk Triggers..............................................................................89
Using Triggers to Insert or Update Records with Unique Fields.....................................................................89
Defining Triggers........................................................................................................................................................89
Triggers and Merge Statements..................................................................................................................................91

ii

Table of Contents
Triggers and Recovered Records.................................................................................................................................92
Triggers and Order of Execution.................................................................................................................................92
Operations That Don't Invoke Triggers......................................................................................................................94
Fields that Arent Available or Cant Be Updated in Triggers.....................................................................................96
Trigger Exceptions......................................................................................................................................................96
Trigger and Bulk Request Best Practices.....................................................................................................................97
Apex Scheduler........................................................................................................................................................................98
Anonymous Blocks................................................................................................................................................................103
Apex in AJAX.......................................................................................................................................................................104

Chapter 4: Classes, Objects, and Interfaces........................................................................................106


Understanding Classes..........................................................................................................................................................107
Defining Apex Classes...............................................................................................................................................107
Extended Class Example...........................................................................................................................................108
Declaring Class Variables..........................................................................................................................................111
Defining Class Methods............................................................................................................................................112
Using Constructors....................................................................................................................................................114
Access Modifiers........................................................................................................................................................116
Static and Instance.....................................................................................................................................................117
Using Static Methods and Variables..............................................................................................................117
Using Instance Methods and Variables..........................................................................................................118
Using Initialization Code...............................................................................................................................119
Apex Properties.........................................................................................................................................................120
Interfaces and Extending Classes..........................................................................................................................................122
Parameterized Typing and Interfaces........................................................................................................................123
Custom Iterators........................................................................................................................................................126
Keywords...............................................................................................................................................................................128
Using the final Keyword............................................................................................................................................128
Using the instanceof Keyword...................................................................................................................................128
Using the super Keyword...........................................................................................................................................128
Using the this Keyword.............................................................................................................................................130
Using the transient Keyword.....................................................................................................................................130
Using the with sharing or without sharing Keywords................................................................................................131
Annotations...........................................................................................................................................................................133
Deprecated Annotation.............................................................................................................................................134
Future Annotation.....................................................................................................................................................134
IsTest Annotation.....................................................................................................................................................136
ReadOnly Annotation...............................................................................................................................................139
RemoteAction Annotation........................................................................................................................................139
Apex REST Annotations..........................................................................................................................................140
RestResource Annotation..............................................................................................................................140
HttpDelete Annotation.................................................................................................................................141
HttpGet Annotation......................................................................................................................................141
HttpPatch Annotation...................................................................................................................................141
HttpPost Annotation.....................................................................................................................................141

iii

Table of Contents
HttpPut Annotation......................................................................................................................................141
Classes and Casting...............................................................................................................................................................142
Classes and Collections.............................................................................................................................................143
Collection Casting.....................................................................................................................................................143
Differences Between Apex Classes and Java Classes.............................................................................................................144
Class Definition Creation......................................................................................................................................................145
Naming Conventions.................................................................................................................................................146
Name Shadowing......................................................................................................................................................147
Class Security........................................................................................................................................................................147
Enforcing Object and Field Permissions...............................................................................................................................148
Namespace Prefix..................................................................................................................................................................149
Using Namespaces When Invoking Methods...........................................................................................................149
Namespace, Class, and Variable Name Precedence...................................................................................................150
Type Resolution and System Namespace for Types..................................................................................................151
Version Settings....................................................................................................................................................................151
Setting the Salesforce API Version for Classes and Triggers....................................................................................151
Setting Package Versions for Apex Classes and Triggers..........................................................................................152

Chapter 5: Testing Apex...................................................................................................................154


Understanding Testing in Apex............................................................................................................................................155
Why Test Apex?........................................................................................................................................................155
What to Test in Apex................................................................................................................................................155
Unit Testing Apex.................................................................................................................................................................156
Isolation of Test Data from Organization Data in Unit Tests..................................................................................157
Using the runAs Method...........................................................................................................................................158
Using Limits, startTest, and stopTest.......................................................................................................................159
Adding SOSL Queries to Unit Tests........................................................................................................................160
Running Unit Test Methods.................................................................................................................................................160
Testing Best Practices...........................................................................................................................................................165
Testing Example...................................................................................................................................................................166

Chapter 6: Dynamic Apex.................................................................................................................171


Understanding Apex Describe Information..........................................................................................................................172
Dynamic SOQL....................................................................................................................................................................180
Dynamic SOSL.....................................................................................................................................................................181
Dynamic DML.....................................................................................................................................................................182

Chapter 7: Batch Apex......................................................................................................................185


Using Batch Apex..................................................................................................................................................................186
Understanding Apex Managed Sharing................................................................................................................................194
Understanding Sharing..............................................................................................................................................195
Sharing a Record Using Apex....................................................................................................................................197
Recalculating Apex Managed Sharing.......................................................................................................................202

Chapter 8: Debugging Apex..............................................................................................................207


Understanding the Debug Log..............................................................................................................................................208

iv

Table of Contents
Using the Developer Console....................................................................................................................................212
Debugging Apex API Calls.......................................................................................................................................220
Handling Uncaught Exceptions............................................................................................................................................222
Understanding Execution Governors and Limits..................................................................................................................222
Using Governor Limit Email Warnings...............................................................................................................................227

Chapter 9: Developing Apex in Managed Packages............................................................................228


Package Versions...................................................................................................................................................................229
Deprecating Apex..................................................................................................................................................................229
Behavior in Package Versions................................................................................................................................................230
Versioning Apex Code Behavior...............................................................................................................................230
Apex Code Items that Are Not Versioned................................................................................................................231
Testing Behavior in Package Versions.......................................................................................................................232

Chapter 10: Exposing Apex Methods as SOAP Web Services..............................................................234


WebService Methods............................................................................................................................................................235
Exposing Data with WebService Methods................................................................................................................235
Considerations for Using the WebService Keyword..................................................................................................235
Overloading Web Service Methods...........................................................................................................................237

Chapter 11: Exposing Apex Classes as REST Web Services................................................................238


Introduction to Apex REST..................................................................................................................................................239
Apex REST Annotations......................................................................................................................................................239
Apex REST Methods............................................................................................................................................................239
Exposing Data with Apex REST Web Service Methods......................................................................................................244
Apex REST Code Samples...................................................................................................................................................245
Apex REST Basic Code Sample...............................................................................................................................245
Apex REST Code Sample Using RestRequest.........................................................................................................246

Chapter 12: Invoking Callouts Using Apex........................................................................................248


Adding Remote Site Settings................................................................................................................................................249
SOAP Services: Defining a Class from a WSDL Document...............................................................................................249
Invoking an External Service.....................................................................................................................................250
HTTP Header Support.............................................................................................................................................250
Supported WSDL Features.......................................................................................................................................251
Understanding the Generated Code..........................................................................................................................253
Test Coverage for the Generated Code.....................................................................................................................256
Considerations Using WSDLs..................................................................................................................................257
Mapping Headers..........................................................................................................................................258
Understanding Runtime Events.....................................................................................................................258
Understanding Unsupported Characters in Variable Names.........................................................................258
Debugging Classes Generated from WSDL Files.........................................................................................258
Invoking HTTP Callouts......................................................................................................................................................258
Using Certificates..................................................................................................................................................................259
Generating Certificates..............................................................................................................................................259
Using Certificates with SOAP Services.....................................................................................................................260

Table of Contents
Using Certificates with HTTP Requests...................................................................................................................261
Callout Limits.......................................................................................................................................................................261

Chapter 13: Reference.......................................................................................................................263


Apex Data Manipulation Language (DML) Operations......................................................................................................264
ConvertLead Operation............................................................................................................................................265
Delete Operation.......................................................................................................................................................268
Insert Operation........................................................................................................................................................270
Merge Statement.......................................................................................................................................................273
Undelete Operation...................................................................................................................................................274
Update Operation......................................................................................................................................................276
Upsert Operation.......................................................................................................................................................278
sObjects That Do Not Support DML Operations....................................................................................................282
sObjects That Cannot Be Used Together in DML Operations................................................................................283
Bulk DML Exception Handling...............................................................................................................................285
Apex Standard Classes and Methods....................................................................................................................................285
Apex Primitive Methods...........................................................................................................................................286
Blob Methods................................................................................................................................................286
Boolean Methods...........................................................................................................................................287
Date Methods................................................................................................................................................287
Datetime Methods.........................................................................................................................................290
Decimal Methods..........................................................................................................................................295
Double Methods............................................................................................................................................300
Integer Methods............................................................................................................................................301
Long Methods...............................................................................................................................................302
String Methods..............................................................................................................................................302
Time Methods...............................................................................................................................................308
Apex Collection Methods..........................................................................................................................................309
List Methods.................................................................................................................................................309
Map Methods................................................................................................................................................316
Set Methods...................................................................................................................................................320
Enum Methods.........................................................................................................................................................323
Apex sObject Methods..............................................................................................................................................324
Schema Methods...........................................................................................................................................324
sObject Methods............................................................................................................................................328
sObject Describe Result Methods.................................................................................................................332
Describe Field Result Methods.....................................................................................................................336
Schema.FieldSet Methods.............................................................................................................................343
Custom Settings Methods.............................................................................................................................346
Apex System Methods...............................................................................................................................................354
ApexPages Methods......................................................................................................................................354
Approval Methods.........................................................................................................................................355
Database Methods.........................................................................................................................................356
JSON Support...............................................................................................................................................370
Limits Methods.............................................................................................................................................387

vi

Table of Contents
Math Methods...............................................................................................................................................390
Apex REST...................................................................................................................................................394
Search Methods.............................................................................................................................................400
System Methods............................................................................................................................................400
Test Methods.................................................................................................................................................411
Type Methods...............................................................................................................................................414
URL Methods...............................................................................................................................................417
UserInfo Methods..........................................................................................................................................420
Version Methods...........................................................................................................................................421
Using Exception Methods.........................................................................................................................................423
Apex Classes..........................................................................................................................................................................426
Apex Email Classes...................................................................................................................................................426
Outbound Email............................................................................................................................................426
Inbound Email...............................................................................................................................................437
Exception Class.........................................................................................................................................................442
Constructing an Exception............................................................................................................................443
Using Exception Variables.............................................................................................................................444
Visualforce Classes.....................................................................................................................................................444
Action Class...................................................................................................................................................445
Dynamic Component Methods and Properties.............................................................................................446
IdeaStandardController Class........................................................................................................................447
IdeaStandardSetController Class...................................................................................................................450
KnowledgeArticleVersionStandardController Class......................................................................................454
Message Class................................................................................................................................................457
PageReference Class......................................................................................................................................458
SelectOption Class.........................................................................................................................................463
StandardController Class...............................................................................................................................466
StandardSetController Class..........................................................................................................................468
Pattern and Matcher Classes.....................................................................................................................................470
Using Patterns and Matchers.........................................................................................................................471
Using Regions................................................................................................................................................472
Using Match Operations...............................................................................................................................472
Using Bounds................................................................................................................................................472
Understanding Capturing Groups.................................................................................................................473
Pattern and Matcher Example.......................................................................................................................473
Pattern Methods............................................................................................................................................474
Matcher Methods..........................................................................................................................................476
HTTP (RESTful) Services Classes...........................................................................................................................481
HTTP Classes...............................................................................................................................................482
Crypto Class..................................................................................................................................................488
EncodingUtil Class........................................................................................................................................494
XML Classes.............................................................................................................................................................496
XmlStream Classes........................................................................................................................................496
DOM Classes................................................................................................................................................503
Apex Approval Processing Classes............................................................................................................................509

vii

Table of Contents
Apex Approval Processing Example..............................................................................................................509
ProcessRequest Class.....................................................................................................................................510
ProcessResult Class........................................................................................................................................511
ProcessSubmitRequest Class.........................................................................................................................511
ProcessWorkitemRequest Class....................................................................................................................512
BusinessHours Class..................................................................................................................................................513
Apex Community Classes..........................................................................................................................................515
Answers Class................................................................................................................................................515
Ideas Class.....................................................................................................................................................516
Knowledge Management Publishing Service Class...................................................................................................519
Site Class...................................................................................................................................................................523
Cookie Class..............................................................................................................................................................528
Apex Interfaces......................................................................................................................................................................531
Auth.RegistrationHandler Interface..........................................................................................................................532
Comparable Interface................................................................................................................................................535
InstallHandler Interface.............................................................................................................................................536
Site.UrlRewriter Interface..........................................................................................................................................539
Using the Process.Plugin Interface............................................................................................................................545
Process.Plugin Interface.................................................................................................................................546
Process.PluginRequest Class..........................................................................................................................547
Process.PluginResult Class............................................................................................................................548
Process.PluginDescribeResult Class..............................................................................................................548
Process.Plugin Data Type Conversions.........................................................................................................551
Sample Process.Plugin Implementation for Lead Conversion.......................................................................552
UninstallHandler Interface........................................................................................................................................558

Chapter 14: Deploying Apex.............................................................................................................560


Using Change Sets To Deploy Apex.....................................................................................................................................561
Using the Force.com IDE to Deploy Apex...........................................................................................................................561
Using the Force.com Migration Tool....................................................................................................................................561
Understanding deploy................................................................................................................................................563
Understanding retrieveCode......................................................................................................................................565
Understanding runTests()..........................................................................................................................................566
Using SOAP API to Deploy Apex........................................................................................................................................566

Appendices......................................................................................................................................568
Appendix A: Shipping Invoice Example....................................................................................568
Shipping Invoice Example Walk-Through...............................................................................................................568
Shipping Invoice Example Code...............................................................................................................................571

Appendix B: Reserved Keywords..............................................................................................580


Appendix C: Security Tips for Apex and Visualforce Development.............................................582

viii

Table of Contents
Cross Site Scripting (XSS)........................................................................................................................................582
Unescaped Output and Formulas in Visualforce Pages.............................................................................................584
Cross-Site Request Forgery (CSRF).........................................................................................................................585
SOQL Injection........................................................................................................................................................586
Data Access Control..................................................................................................................................................588

Appendix D: SOAP API and SOAP Headers for Apex..............................................................590


ApexTestQueueItem.................................................................................................................................................591
ApexTestResult.........................................................................................................................................................592
compileAndTest()......................................................................................................................................................595
CompileAndTestRequest..............................................................................................................................596
CompileAndTestResult.................................................................................................................................597
compileClasses()........................................................................................................................................................599
compileTriggers()......................................................................................................................................................600
executeanonymous()..................................................................................................................................................600
ExecuteAnonymousResult.............................................................................................................................601
runTests()..................................................................................................................................................................601
RunTestsRequest...........................................................................................................................................603
RunTestsResult..............................................................................................................................................603
DebuggingHeader.....................................................................................................................................................607
PackageVersionHeader..............................................................................................................................................608

Glossary...........................................................................................................................................610
Index...............................................................................................................................................628

ix

Table of Contents

Chapter 1
Introducing Apex
In this chapter ...

What is Apex?
What's New?
Apex Quick Start

Salesforce.com has changed the way organizations do business by moving


enterprise applications that were traditionally client-server-based into an
on-demand, multitenant Web environment, the Force.com platform. This
environment allows organizations to run and customize applications, such as
Salesforce Automation and Service & Support, and build new custom applications
based on particular business needs.
While many customization options are available through the Salesforce user
interface, such as the ability to define new fields, objects, workflow, and approval
processes, developers can also use the SOAP API to issue data manipulation
commands such as delete(), update() or upsert(), from client-side
programs.
These client-side programs, typically written in Java, JavaScript, .NET, or other
programming languages grant organizations more flexibility in their
customizations. However, because the controlling logic for these client-side
programs is not located on Force.com platform servers, they are restricted by:

The performance costs of making multiple round-trips to the salesforce.com


site to accomplish common business transactions
The cost and complexity of hosting server code, such as Java or .NET, in a
secure and robust environment

To address these issues, and to revolutionize the way that developers create
on-demand applications, salesforce.com introduces Force.com Apex code, the
first multitenant, on-demand programming language for developers interested
in building the next generation of business applications.

What is Apex?more about when to use Apex, the development process,


and some limitations
What's new in this Apex release?
Apex Quick Startdelve straight into the code and write your first Apex
class and trigger

11

Introducing Apex

What is Apex?

What is Apex?
Apex is a strongly typed, object-oriented programming language that allows developers to execute flow and transaction control
statements on the Force.com platform server in conjunction with calls to the Force.com API. Using syntax that looks like Java
and acts like database stored procedures, Apex enables developers to add business logic to most system events, including button
clicks, related record updates, and Visualforce pages. Apex code can be initiated by Web service requests and from triggers on
objects.

Figure 1: You can add Apex to most system events.


As a language, Apex is:
Integrated
Apex provides built-in support for common Force.com platform idioms, including:

Data manipulation language (DML) calls, such as INSERT, UPDATE, and DELETE, that include built-in
DmlException handling
Inline Salesforce Object Query Language (SOQL) and Salesforce Object Search Language (SOSL) queries that
return lists of sObject records
Looping that allows for bulk processing of multiple records at a time
Locking syntax that prevents record update conflicts
Custom public Force.com API calls that can be built from stored Apex methods

12

Introducing Apex

How Does Apex Work?

Warnings and errors issued when a user tries to edit or delete a custom object or field that is referenced by Apex

Easy to use
Apex is based on familiar Java idioms, such as variable and expression syntax, block and conditional statement syntax,
loop syntax, object and array notation, and so on. Where Apex introduces new elements, it uses syntax and semantics
that are easy to understand and encourage efficient use of the Force.com platform. Consequently, Apex produces code
that is both succinct and easy to write.
Data focused
Apex is designed to thread together multiple query and DML statements into a single unit of work on the Force.com
platform server, much as developers use database stored procedures to thread together multiple transaction statements
on a database server. Note that like other database stored procedures, Apex does not attempt to provide general support
for rendering elements in the user interface.
Rigorous
Apex is a strongly-typed language that uses direct references to schema objects such as object and field names. It fails
quickly at compile time if any references are invalid, and stores all custom field, object, and class dependencies in metadata
to ensure they are not deleted while required by active Apex code.
Hosted
Apex is interpreted, executed, and controlled entirely by the Force.com platform.
Multitenant aware
Like the rest of the Force.com platform, Apex runs in a multitenant environment. Consequently, the Apex runtime
engine is designed to guard closely against runaway code, preventing them from monopolizing shared resources. Any
code that violate these limits fail with easy-to-understand error messages.
Automatically upgradeable
Apex never needs to be rewritten when other parts of the Force.com platform are upgraded. Because the compiled code
is stored as metadata in the platform, it always gets automatically upgraded with the rest of the system.
Easy to test
Apex provides built-in support for unit test creation and execution, including test results that indicate how much code
is covered, and which parts of your code could be more efficient. Salesforce.com ensures that Apex code always work as
expected by executing all unit tests stored in metadata prior to any platform upgrades.
Versioned
You can save your Apex code against different versions of the Force.com API. This enables you to maintain behavior.
Apex is included in Unlimited Edition, Developer Edition, Enterprise Edition, and Database.com.

How Does Apex Work?


All Apex runs entirely on-demand on the Force.com platform, as shown in the following architecture diagram:

13

Introducing Apex

What is the Apex Development Process?

Figure 2: Apex is compiled, stored, and run entirely on the Force.com platform.
When a developer writes and saves Apex code to the platform, the platform application server first compiles the code into an
abstract set of instructions that can be understood by the Apex runtime interpreter, and then saves those instructions as
metadata.
When an end-user triggers the execution of Apex, perhaps by clicking a button or accessing a Visualforce page, the platform
application server retrieves the compiled instructions from the metadata and sends them through the runtime interpreter before
returning the result. The end-user observes no differences in execution time from standard platform requests.

What is the Apex Development Process?


We recommend the following process for developing Apex:
1. Sign up for a Database.com Edition account and create a sandbox organization. For more information about sandbox
organizations, see Using a Developer or Sandbox Organization.
2. Learn more about Apex.
3. Write your Apex.
4. While writing Apex, you should also be writing tests.
5. Optionally deploy your Apex to a sandbox organization and do final unit tests.
6. Deploy your Apex to your Salesforce production organization.
In addition to deploying your Apex, once it is written and tested, you can also add your classes and triggers to a Force.com
AppExchange App package.
Using a Developer or Sandbox Organization
There are three types of organizations where you can run your Apex:

A developer organization: an organization created with a Developer Edition account.


A production organization: an organization that has live users accessing your data.

14

Introducing Apex

What is the Apex Development Process?

A sandbox organization: an organization created on your production organization that is a copy of your production
organization.
Note: Apex triggers are available in the Trial Edition of Salesforce; however, they are disabled when you convert to
any other edition. If your newly-signed-up organization includes Apex, you must deploy your code to your organization
using one of the deployment methods.

You can't develop Apex in your Salesforce production organization. Live users accessing the system while you're developing
can destabilize your data or corrupt your application. Instead, we recommend that you do all your development work in either
a sandbox or a Developer Edition organization.
If you aren't already a member of the developer community, go to http://developer.force.com/join and follow the
instructions to sign up for a Developer Edition account. A Developer Edition account gives you access to a free Developer
Edition organization. Even if you already have an Enterprise or Unlimited Edition organization and a sandbox for creating
Apex, we strongly recommends that you take advantage of the resources available in the developer community.
Note: You cannot make changes to Apex using the Salesforce user interface in a Salesforce production organization.

Creating a Sandbox Organization


To create or refresh a sandbox organization:
1. Click Your Name > Setup > Data Management > Sandbox.
2. Do one of the following:

Click New Sandbox. For information on different kinds of sandboxes, see Sandbox Overview in the online help.

Salesforce deactivates the New Sandbox button when an organization reaches its sandbox limit. If necessary, contact
salesforce.com to order more sandboxes for your organization.
Note that Salesforce deactivates all refresh links if you have exceeded your sandbox limit.
Click Refresh to replace an existing sandbox with a new copy. Salesforce only displays the Refresh link for sandboxes
that are eligible for refreshing. For full-copy sandboxes, this is any time after 30 days from the previous creation or
refresh of that sandbox. For configuration-only sandboxes (including developer sandboxes), you can refresh once per
day. Your existing copy of this sandbox remains available while you wait for the refresh to complete. The refreshed
copy is inactive until you activate it.

3. Enter a name and description for the sandbox. You can only change the name when you create or refresh a sandbox.
Tip: We recommend that you choose a name that:

Reflects the purpose of this sandbox, such as QA.


Has few characters because Salesforce automatically appends the sandbox name to usernames and email addresses
on user records in the sandbox environment. Names with fewer characters make sandbox logins easier to type.

4. Select the type of sandbox:

Configuration Only: Configuration-only sandboxes copy all of your production organization's reports, dashboards,
price books, products, apps, and customizations under Your Name > Setup, but exclude all of your organization's
standard and custom object records, documents, and attachments. Creating a configuration-only sandbox can decrease
the time it takes to create or refresh a sandbox from several hours to just a few minutes, but it can only include up to
500 MB of data. You can refresh a configuration-only sandbox once per day.
Developer: Developer sandboxes are special configuration-only sandboxes intended for coding and testing by a single
developer. They provide an environment in which changes under active development can be isolated until they are

15

Introducing Apex

What is the Apex Development Process?

ready to be shared. Just like configuration-only sandboxes, developer sandboxes copy all application and configuration
information to the sandbox. Developer sandboxes are limited to 10 MB of test or sample data, which is enough for
many development and testing tasks. You can refresh a developer sandbox once per day.
Full: Full sandboxes copy your entire production organization and all its data, including standard and custom object
records, documents, and attachments. You can refresh a full-copy sandbox every 29 days.

If you have reduced the number of sandboxes you purchased, but you still have more sandboxes of a specific type than
allowed, you will be required to match your sandboxes to the number of sandboxes that you purchased. For example, if
you have two full sandboxes but purchased only one, you cannot refresh your full sandbox as a full sandbox. Instead, you
must choose one full sandbox to convert to a smaller sandbox, such as configuration-only or developer sandbox, depending
on which type of sandbox you have available.
Note: Configuration-only and developer sandboxes copy all of your production organization's reports, dashboards,
price books, products, apps, and customizations under Your Name > Setup, but exclude all of your organization's
standard and custom object records, documents, and attachments. Because they copy much less data, creating these
sandbox types can substantially decrease the time it takes to create or refresh a sandbox.
If you are refreshing an existing sandbox, the radio button usually preselects the sandbox type corresponding to the sandbox
you are refreshing. For example, if you refresh a configuration-only sandbox, the radio button preselects Configuration
Only.
Whether refreshing an existing sandbox or creating a new one, some radio buttons may be disabled if you have already
created the number of sandboxes of that sandbox type allowed for your organization.
5. For a full sandbox, choose how much object history and case history to copy, and whether or not to copy Chatter data.
Object history is the field history tracking of custom and most standard objects, and case history serves the same purpose
for cases. You can copy from 0 to 180 days of object and case history, in 30day increments. The default value is 30 days.
Chatter data includes feeds, messages, and discovery topics. Decreasing the amount of data you copy can significantly
speed up sandbox copy time.
6. Click Start Copy.
The process may take several minutes, hours, or even days, depending on the size of your organization and whether you
are creating a full copy or configuration-only copy.
Tip: You should try to limit changes in your production organization while the sandbox copy proceeds.

7. You will receive a notification email when your newly created or refreshed sandbox has completed copying. If you are
creating a new sandbox, the newly created sandbox is now ready for use.
If you are refreshing an existing sandbox, an additional step is required to complete the sandbox copy process. The new
sandbox must be activated. To delete your existing sandbox and activate the new one:
a. Return to the sandbox list by logging into your production organization and navigating to Your Name > Setup > Data
Management > Sandbox.
b. Click the Activate link next to the sandbox you wish to activate.
This will take you to a page warning of removal of your existing sandbox.
c. Read the warning carefully and if you agree to the removal, enter the acknowledgment text at the prompt and click the
Activate button.
When the activation process is complete, you will receive a notification email.
Caution: Activating a replacement sandbox that was created using the Refresh link completely deletes the sandbox
it is refreshing. All configuration and data in the prior sandbox copy will be lost, including any application or data
changes you have made. Please read the warning carefully, and press the Activate link only if you have no further

16

Introducing Apex

What is the Apex Development Process?

need for the contents of the sandbox copy currently in use. Your production organization and its data will not be
affected.
8. Once your new sandbox is complete, or your refreshed sandbox is activated, you can click the link in the notification email
to access your sandbox.
You can log into the sandbox at test.salesforce.com/login.jsp by appending .sandbox_name to your Salesforce
username. For example, if your username for your production organization is [email protected], then your username for
a sandbox named test is [email protected]. For more information, see Username and Email Address Modification
in the online help.
Note: Salesforce automatically changes sandbox usernames but does not change passwords.

Learning Apex
After you have your developer account, there are many resources available to you for learning about Apex:
Force.com Workbook: Get Started Building Your First App in the Cloud
Beginning programmers
A set of ten 30-minute tutorials that introduce various Force.com platform features. The Force.com Workbook tutorials
are centered around building a very simple warehouse management system. You'll start developing the application from
the bottom up; that is, you'll first build a database model for keeping track of merchandise. You'll continue by adding
business logic: validation rules to ensure that there is enough stock, workflow to update inventory when something is
sold, approvals to send email notifications for large invoice values, and trigger logic to update the prices in open invoices.
Once the database and business logic are complete, you'll create a user interface to display a product inventory to staff,
a public website to display a product catalog, and then the start of a simple store front. If you'd like to develop offline
and integrate with the app, we've added a final tutorial to use Adobe Flash Builder for Force.com.
Force.com Workbook: HTML | PDF
Apex Workbook
Beginning programmers
The Apex Workbook introduces you to the Apex programming language through a set of tutorials. Youll learn the
fundamentals of Apex and how you can use it on the Force.com platform to add custom business logic through triggers,
unit tests, scheduled Apex, batch Apex, REST Web services, and Visualforce controllers.
Apex Workbook: HTML | PDF
Developer Force Apex Page
Beginning and advanced programmers
The Apex page on Developer Force has links to several resources including articles about the Apex programming language.
These resources provide a quick introduction to Apex and include best practices for Apex development.
Force.com Cookbook
Beginning and advanced programmers
This collaborative site provides many recipes for using the Web services API, developing Apex code, and creating
Visualforce pages. The Force.com Cookbook helps developers become familiar with common Force.com programming

17

Introducing Apex

What is the Apex Development Process?

techniques and best practices. You can read and comment on existing recipes, or submit your own recipes, at
developer.force.com/cookbook.
Development Life Cycle: Enterprise Development on the Force.com Platform
Architects and advanced programmers
Whether you are an architect, administrator, developer, or manager, the Development Life Cycle Guide prepares you to
undertake the development and release of complex applications on the Force.com platform.
Training Courses
Training classes are also available from salesforce.com Training & Certification. You can find a complete list of courses
at www.salesforce.com/training.
In This Book (Apex Developer's Guide)
Beginning programmers should look at the following:

Introducing Apex, and in particular:


Documentation Conventions
Core Concepts
Quick Start Tutorial

Classes, Objects, and Interfaces


Testing Apex
Understanding Execution Governors and Limits

In addition to the above, advanced programmers should look at:

Trigger and Bulk Request Best Practices


Advanced Apex Programming Example
Understanding Apex Describe Information
Asynchronous Execution (@future Annotation)
Batch Apex and Apex Scheduler

Writing Apex
You can write Apex code and tests in any of the following editing environments:

The Force.com IDE is a plug-in for the Eclipse IDE. The Force.com IDE provides a unified interface for building and
deploying Force.com applications. Designed for developers and development teams, the IDE provides tools to accelerate
Force.com application development, including source code editors, test execution tools, wizards and integrated help. This
tool includes basic color-coding, outline view, integrated unit testing, and auto-compilation on save with error message
display. See the website for information about installation and usage.
Note: The Force.com IDE is a free resource provided by salesforce.com to support its users and partners but isn't
considered part of our services for purposes of the salesforce.com Master Subscription Agreement.

The Salesforce user interface. All classes and triggers are compiled when they are saved, and any syntax errors are flagged.
You cannot save your code until it compiles without errors. The Salesforce user interface also numbers the lines in the
code, and uses color coding to distinguish different elements, such as comments, keywords, literal strings, and so on.

18

Introducing Apex

What is the Apex Development Process?

For a trigger on a standard object, click Your Name > Setup > Customize, click the name of the object, and click
Triggers. In the Triggers detail page, click New, and then enter your code in the Body text box.
For a trigger on a custom object, click Your Name > Setup > Develop > Objects, and click the name of the object. In
the Triggers related list, click New, and then enter your code in the Body text box.
For a class, click Your Name > Setup > Develop > Apex Classes. Click New, and then enter your code in the Body
text box.
Note: You cannot make changes to Apex using the Salesforce user interface in a Salesforce production organization.

Any text editor, such as Notepad. You can write your Apex code, then either copy and paste it into your application, or
use one of the API calls to deploy it.
Tip: If you want to extend the Eclipse plug-in or develop an Apex IDE of your own, the SOAP API includes methods
for compiling triggers and classes, and executing test methods, while the Metadata API includes methods for deploying
code to production environments. For more information, see Deploying Apex on page 560 and SOAP API and SOAP
Headers for Apex on page 590.

Writing Tests
Testing is the key to successful long term development, and is a critical component of the development process. We strongly
recommend that you use a test-driven development process, that is, test development that occurs at the same time as code
development.
To facilitate the development of robust, error-free code, Apex supports the creation and execution of unit tests. Unit tests are
class methods that verify whether a particular piece of code is working properly. Unit test methods take no arguments, commit
no data to the database, send no emails, and are flagged with the testMethod keyword in the method definition.
In addition, before you deploy Apex or package it for the Force.com AppExchange, the following must be true:

75% of your Apex code must be covered by unit tests, and all of those tests must complete successfully.
Note the following:

When deploying to a production organization, every unit test in your organization namespace is executed.
Calls to System.debug are not counted as part of Apex code coverage.
Test methods and test classes are not counted as part of Apex code coverage.
While only 75% of your Apex code must be covered by tests, your focus shouldn't be on the percentage of code that is
covered. Instead, you should make sure that every use case of your application is covered, including positive and negative
cases, as well as bulk and single record. This should lead to 75% or more of your code being covered by unit tests.

Every trigger has some test coverage.


All classes and triggers compile successfully.

For more information on writing tests, see Testing Apex on page 154.
Deploying Apex to a Sandbox Organization
Salesforce gives you the ability to create multiple copies of your organization in separate environments for a variety of purposes,
such as testing and training, without compromising the data and applications in your Salesforce production organization.
These copies are called sandboxes and are nearly identical to your Salesforce production organization. Sandboxes are completely

19

Introducing Apex

What is the Apex Development Process?

isolated from your Salesforce production organization, so operations you perform in your sandboxes do not affect your Salesforce
production organization, and vice versa.
To deploy Apex from a local project in the Force.com IDE to a Salesforce organization, use the Force.com Component
Deployment Wizard. For more information about the Force.com IDE, see
http://wiki.developerforce.com/index.php/Force.com_IDE.
You can also use the deploy() Metadata API call to deploy your Apex from a developer organization to a sandbox organization.
A useful API call is runTests(). In a development or sandbox organization, you can run the unit tests for a specific class, a
list of classes, or a namespace.
Salesforce includes a Force.com Migration Tool that allows you to issue these commands in a console window, or your can
implement your own deployment code.
Note: The Force.com IDE and the Force.com Migration Tool are free resources provided by salesforce.com to support
its users and partners, but aren't considered part of our services for purposes of the salesforce.com Master Subscription
Agreement.
For more information, see Using the Force.com Migration Tool and Deploying Apex.
Deploying Apex to a Salesforce Production Organization
After you have finished all of your unit tests and verified that your Apex code is executing properly, the final step is deploying
Apex to your Salesforce production organization.
To deploy Apex from a local project in the Force.com IDE to a Salesforce organization, use the Force.com Component
Deployment Wizard. For more information about the Force.com IDE, see
http://wiki.developerforce.com/index.php/Force.com_IDE.
Also, you can deploy Apex through change sets in the Salesforce user interface.
For more information and for additional deployment options, see Deploying Apex on page 560.
Adding Apex Code to a Force.com AppExchange App
You can also include an Apex class or trigger in an app that you are creating for AppExchange.
Any Apex that is included as part of a package must have at least 75% cumulative test coverage. Each trigger must also have
some test coverage. When you upload your package to AppExchange, all tests are run to ensure that they run without errors.
In addition, tests with the@isTest(OnInstall=true) annotation run when the package is installed in the installer's
organization. You can specify which tests should run during package install by annotating them with
@isTest(OnInstall=true). This subset of tests must pass for the package install to succeed.
In addition, salesforce.com recommends that any AppExchange package that contains Apex be a managed package.
For more information, see the Force.com Quick Reference for Developing Packages. For more information about Apex in managed
packages, see Developing Apex in Managed Packages on page 228.
Note: Packaging Apex classes that contain references to custom labels which have translations: To include the
translations in the package, enable the Translation Workbench and explicitly package the individual languages used
in the translated custom labels. See Custom Labels Overview in the online help.

20

Introducing Apex

When Should I Use Apex?

When Should I Use Apex?


The Salesforce prebuilt applications provide powerful CRM functionality. In addition, Salesforce provides the ability to
customize the prebuilt applications to fit your organization. However, your organization may have complex business processes
that are unsupported by the existing functionality. When this is the case, the Force.com platform includes a number of ways
for advanced administrators and developers to implement custom functionality. These include Apex, Visualforce, and the
SOAP API.

Apex
Use Apex if you want to:

Create Web services.


Create email services.
Perform complex validation over multiple objects.
Create complex business processes that are not supported by workflow.
Create custom transactional logic (logic that occurs over the entire transaction, not just with a single record or object.)
Attach custom logic to another operation, such as saving a record, so that it occurs whenever the operation is executed,
regardless of whether it originates in the user interface, a Visualforce page, or from SOAP API.

Visualforce
Visualforce consists of a tag-based markup language that gives developers a more powerful way of building applications and
customizing the Salesforce user interface. With Visualforce you can:

Build wizards and other multistep processes.


Create your own custom flow control through an application.
Define navigation patterns and data-specific rules for optimal, efficient application interaction.

For more information, see the Visualforce Developer's Guide.

SOAP API
Use standard SOAP API calls if you want to add functionality to a composite application that processes only one type of
record at a time and does not require any transactional control (such as setting a Savepoint or rolling back changes).
For more information, see the SOAP API Developer's Guide.

What are the Limitations of Apex?


Apex radically changes the way that developers create on-demand business applications, but it is not currently meant to be a
general purpose programming language. As of this release, Apex cannot be used to:

Render elements in the user interface other than error messages


Change standard functionalityApex can only prevent the functionality from happening, or add additional functionality
Create temporary files
Spawn threads
Tip:
All Apex runs on the Force.com platform, which is a shared resource used by all other organizations. To guarantee
consistent performance and scalability, the execution of Apex is bound by governor limits that ensure no single Apex

21

Introducing Apex

What's New?

execution impacts the overall service of Salesforce. This means all Apex code is limited by the number of operations
(such as DML or SOQL) that it can perform within one process.
All Apex requests return a collection that contains from 1 to 50,000 records. You cannot assume that your code only
works on a single record at a time. Therefore, you must implement programming patterns that take bulk processing
into account. If you do not, you may run into the governor limits.

See Also:
Understanding Execution Governors and Limits
Trigger and Bulk Request Best Practices

What's New?
Review the Summer '12 Release Notes for a summary of new and changed Apex features in Summer '12.

Apex Quick Start


Once you have a Developer Edition or sandbox organization, you may want to learn some of the core concepts of Apex.
Because Apex is very similar to Java, you may recognize much of the functionality.
After reviewing the basics, you are ready to write your first Apex programa very simple class, trigger, and unit test.
In addition, there is a more complex shipping invoice example that you can also walk through. This example illustrates many
more features of the language.
Note: The Hello World and the shipping invoice samples require custom fields and objects. You can either create
these on your own, or download the objects, fields and Apex code as a managed packaged from Force.com AppExchange.
For more information, see wiki.developerforce.com/index.php/Documentation.

Documentation Typographical Conventions


Apex and Visualforce documentation uses the following typographical conventions.
Convention

Description

Courier font

In descriptions of syntax, monospace font indicates items that you should type as shown,
except for brackets. For example:
Public class HelloWorld

22

Introducing Apex

Understanding Apex Core Concepts

Convention

Description

Italics

In description of syntax, italics represent variables. You supply the actual value. In the
following example, three values need to be supplied: datatype variable_name [ =
value];
If the syntax is bold and italic, the text represents a code element that needs a value
supplied by you, such as a class name or variable value:
public static class YourClassHere { ... }

<>

In descriptions of syntax, less-than and greater-than symbols (< >) are typed exactly as
shown.
<apex:pageBlockTable value="{!account.Contacts}" var="contact">
<apex:column value="{!contact.Name}"/>
<apex:column value="{!contact.MailingCity}"/>
<apex:column value="{!contact.Phone}"/>
</apex:pageBlockTable>

{}

In descriptions of syntax, braces ({ }) are typed exactly as shown.


<apex:page>
Hello {!$User.FirstName}!
</apex:page>

[]

In descriptions of syntax, anything included in brackets is optional. In the following


example, specifying value is optional:
data_type variable_name [ = value];

In descriptions of syntax, the pipe sign means or. You can do one of the following
(not all). In the following example, you can create a new unpopulated set in one of two
ways, or you can populate the set:
Set<data_type> set_name
[= new Set<data_type>();] |
[= new Set<data_type{value [, value2. . .] };] |
;

Understanding Apex Core Concepts


Apex code typically contains many things that you might be familiar with from other programming languages:

23

Introducing Apex

Understanding Apex Core Concepts

Figure 3: Programming elements in Apex


The section describes the basic functionality of Apex, as well as some of the core concepts.

Using Version Settings


In the Salesforce user interface you can specify a version of the Salesforce.com API against which to save your Apex class or
trigger. This setting indicates not only the version of SOAP API to use, but which version of Apex as well. You can change
the version after saving. Every class or trigger name must be unique. You cannot save the same class or trigger against different
versions.
You can also use version settings to associate a class or trigger with a particular version of a managed package that is installed
in your organization from AppExchange. This version of the managed package will continue to be used by the class or trigger
if later versions of the managed package are installed, unless you manually update the version setting. To add an installed
managed package to the settings list, select a package from the list of available packages. The list is only displayed if you have
an installed managed package that is not already associated with the class or trigger.

For more information about using version settings with managed packages, see About Package Versions in the Salesforce
online help.

24

Introducing Apex

Understanding Apex Core Concepts

Naming Variables, Methods and Classes


You cannot use any of the Apex reserved keywords when naming variables, methods or classes. These include words that are
part of Apex and the Force.com platform, such as list, test, or account, as well as reserved keywords.

Using Variables and Expressions


Apex is a strongly-typed language, that is, you must declare the data type of a variable when you first refer to it. Apex data types
include basic types such as Integer, Date, and Boolean, as well as more advanced types such as lists, maps, objects and sObjects.
Variables are declared with a name and a data type. You can assign a value to a variable when you declare it. You can also
assign values later. Use the following syntax when declaring variables:
datatype variable_name [ = value];

Tip: Note that the semi-colon at the end of the above is not optional. You must end all statements with a semi-colon.

The following are examples of variable declarations:


// The following variable has the data type of Integer with the name Count,
// and has the value of 0.
Integer Count = 0;
// The following variable has the data type of Decimal with the name Total. Note
// that no value has been assigned to it.
Decimal Total;
// The following variable is an account, which is also referred to as an sObject.
Account MyAcct = new Account();

In Apex, all primitive data type arguments, such as Integer or String, are passed into methods by value. This means that any
changes to the arguments exist only within the scope of the method. When the method returns, the changes to the arguments
are lost.
Non-primitive data type arguments, such as sObjects, are also passed into methods by value. This means that when the method
returns, the passed-in argument still references the same object as before the method call and can't be changed to point to
another object. However, the values of the object's fields can be changed in the method.

Using Statements
A statement is any coded instruction that performs an action.
In Apex, statements must end with a semicolon and can be one of the following types:

Assignment, such as assigning a value to a variable


Conditional (if-else)
Loops:
Do-while
While
For

Locking
Data Manipulation Language (DML)
Transaction Control
Method Invoking
Exception Handling

25

Introducing Apex

Understanding Apex Core Concepts

A block is a series of statements that are grouped together with curly braces and can be used in any place where a single statement
would be allowed. For example:
if (true) {
System.debug(1);
System.debug(2);
} else {
System.debug(3);
System.debug(4);
}

In cases where a block consists of only one statement, the curly braces can be left off. For example:
if (true)
System.debug(1);
else
System.debug(2);

Using Collections
Apex has the following types of collections:

Lists (arrays)
Maps
Sets

A list is a collection of elements, such as Integers, Strings, objects, or other collections. Use a list when the sequence of elements
is important. You can have duplicate elements in a list.
The first index position in a list is always 0.
To create a list:

Use the new keyword


Use the List keyword followed by the element type contained within <> characters.

Use the following syntax for creating a list:


List <datatype> list_name
[= new List<datatype>();] |
[=new List<datatype>{value [, value2. . .]};] |
;

The following example creates a list of Integer, and assigns it to the variable My_List. Remember, because Apex is strongly
typed, you must declare the data type of My_List as a list of Integer.
List<Integer> My_List = new List<Integer>();

For more information, see Lists on page 43.


A set is a collection of unique, unordered elements. It can contain primitive data types, such as String, Integer, Date, and so
on. It can also contain more complex data types, such as sObjects.
To create a set:

Use the new keyword


Use the Set keyword followed by the primitive data type contained within <> characters

26

Introducing Apex

Understanding Apex Core Concepts

Use the following syntax for creating a set:


Set<datatype> set_name
[= new Set<datatype>();] |
[= new Set<datatype>{value [, value2. . .] };] |
;

The following example creates a set of String. The values for the set are passed in using the curly braces {}.
Set<String> My_String = new Set<String>{'a', 'b', 'c'};

For more information, see Sets on page 48.


A map is a collection of key-value pairs. Keys can be any primitive data type. Values can include primitive data types, as well
as objects and other collections. Use a map when finding something by key matters. You can have duplicate values in a map,
but each key must be unique.
To create a map:

Use the new keyword


Use the Map keyword followed by a key-value pair, delimited by a comma and enclosed in <> characters.

Use the following syntax for creating a map:


Map<key_datatype, value_datatype> map_name
[=new map<key_datatype, value_datatype>();] |
[=new map<key_datatype, value_datatype>
{key1_value => value1_value
[, key2_value => value2_value. . .]};] |
;

The following example creates a map that has a data type of Integer for the key and String for the value. In this example, the
values for the map are being passed in between the curly braces {} as the map is being created.
Map<Integer, String> My_Map = new Map<Integer, String>{1 => 'a', 2 => 'b', 3 => 'c'};

For more information, see Maps on page 49.

Using Branching
An if statement is a true-false test that enables your application to do different things based on a condition. The basic syntax
is as follows:
if (Condition){
// Do this if the condition is true
} else {
// Do this if the condition is not true
}

For more information, see Conditional (If-Else) Statements on page 65.

Using Loops
While the if statement enables your application to do things based on a condition, loops tell your application to do the same
thing again and again based on a condition. Apex supports the following types of loops:

27

Introducing Apex

Writing Your First Apex Class and Trigger

Do-while
While
For

A Do-while loop checks the condition after the code has executed.
A While loop checks the condition at the start, before the code executes.
A For loop enables you to more finely control the condition used with the loop. In addition Apex supports traditional For
loops where you set the conditions, as well as For loops that use lists and SOQL queries as part of the condition.
For more information, see Loops on page 65.

Writing Your First Apex Class and Trigger


This step-by-step tutorial shows how to create a simple Apex class and trigger. It also shows how to deploy these components
to a production organization.
This tutorial is based on a custom object called Book that is created in the first step. This custom object is updated through
a trigger.

See Also:
Creating a Custom Object
Adding an Apex Class
Adding an Apex Trigger
Adding a Test Class
Deploying Components to Production
Creating a Custom Object
Prerequisites:
A Salesforce account in a sandbox Unlimited or Enterprise Edition organization, or an account in a Developer organization.
For more information about creating a sandbox organization, see Sandbox Overview in the Salesforce online help. To sign
up for a free Developer organization, see the Developer Edition Environment Sign Up Page.
In this step, you create a custom object called Book with one custom field called Price.
1.
2.
3.
4.
5.

Log into your sandbox or Developer organization.


Click Your Name > Setup > Create > Objects and click New Custom Object.
Enter Book for the label.
Enter Books for the plural label.
Click Save.
Ta dah! You've now created your first custom object. Now let's create a custom field.
6. In the Custom Fields & Relationships section of the Book detail page, click New.
7. Select Number for the data type and click Next.
8. Enter Price for the field label.
9. Enter 16 in the length text box.
10. Enter 2 in the decimal places text box, and click Next.
11. Click Next to accept the default values for field-level security.

28

Introducing Apex

Writing Your First Apex Class and Trigger

12. Click Save.


Youve just created a custom object called Book, and added a custom field to that custom object. Custom objects already have
some standard fields, like Name and CreatedBy, and allow you to add other fields that are more specific to your implementation.
For this tutorial, the Price field is part of our Book object and it is accessed by the Apex class you will write in the next step.

See Also:
Writing Your First Apex Class and Trigger
Adding an Apex Class
Adding an Apex Class
Prerequisites:

A Salesforce account in a sandbox Unlimited or Enterprise Edition organization, or an account in a Developer organization.
The Book custom object

In this step, you add an Apex class that contains a method for updating the book price. This method is called by the trigger
that you will be adding in the next step.
1. Click Your Name > Setup > Develop > Apex Classes and click New.
2. In the class editor, enter this class definition:
public class MyHelloWorld {
}

The previous code is the class definition to which you will be adding one method in the next step. Apex code is generally
contained in classes. This class is defined as public, which means the class is available to other Apex classes and triggers.
For more information, see Classes, Objects, and Interfaces on page 106.
3. Add this method definition between the class opening and closing brackets.
public static void applyDiscount(Book__c[] books) {
for (Book__c b :books){
b.Price__c *= 0.9;
}
}

This method is called applyDiscount, and is both public and static. Because it is a static method, you don't need to
create an instance of the class to access the methodyou can just use the name of the class followed by a dot (.) and the
name of the method. For more information, see Static and Instance on page 117.
This method takes one parameter, a list of Book records, which is assigned to the variable books. Notice the __c in the
object name Book__c. This indicates that it is a custom object that you created. Standard objects that are provided in the
Salesforce application, such as Account, don't end with this postfix.
The next section of code contains the rest of the method definition:
for (Book__c b :books){
b.Price__c *= 0.9;
}

29

Introducing Apex

Writing Your First Apex Class and Trigger

Notice the __c after the field name Price__c. This indicates it is a custom field that you created. Standard fields that are
provided by default in Salesforce are accessed using the same type of dot notation but without the __c, for example, Name
doesn't end with __c in Book__c.Name. The statement b.Price__c *= 0.9; takes the old value of b.Price__c,
multiplies it by 0.9, which means its value will be discounted by 10%, and then stores the new value into the b.Price__c
field. The *= operator is a shortcut. Another way to write this statement is b.Price__c = b.Price__c * 0.9;. See
Understanding Expression Operators on page 56.
4. Click Save to save the new class. You should now have this full class definition.
public class MyHelloWorld {
public static void applyDiscount(Book__c[] books) {
for (Book__c b :books){
b.Price__c *= 0.9;
}
}
}

You now have a class that contains some code which iterates over a list of books and updates the Price field for each book.
This code is part of the applyDiscount static method that is called by the trigger that you will create in the next step.

See Also:
Writing Your First Apex Class and Trigger
Creating a Custom Object
Adding an Apex Trigger
Adding an Apex Trigger
Prerequisites:

A Salesforce account in a sandbox Unlimited or Enterprise Edition organization, or an account in a Developer organization.
The MyHelloWorld Apex class.

In this step, you create a trigger for the Book__c custom object that calls the applyDiscount method of the MyHelloWorld
class that you created in the previous step.
A trigger is a piece of code that executes before or after records of a particular type are inserted, updated, or deleted from the
Force.com platform database. Every trigger runs with a set of context variables that provide access to the records that caused
the trigger to fire. All triggers run in bulk, that is, they process several records at once.
1. Click Your Name > Setup > Create > Objects and click the name of the object you just created, Book.
2. In the triggers section, click New.
3. In the trigger editor, delete the default template code and enter this trigger definition:
trigger HelloWorldTrigger on Book__c (before insert) {
Book__c[] books = Trigger.new;
MyHelloWorld.applyDiscount(books);
}

The first line of code defines the trigger:


trigger HelloWorldTrigger on Book__c (before insert) {

30

Introducing Apex

Writing Your First Apex Class and Trigger

It gives the trigger a name, specifies the object on which it operates, and defines the events that cause it to fire. For example,
this trigger is called HelloWorldTrigger, it operates on the Book__c object, and runs before new books are inserted into
the database.
The next line in the trigger creates a list of book records named books and assigns it the contents of a trigger context
variable called Trigger.new. Trigger context variables such as Trigger.new are implicitly defined in all triggers and
provide access to the records that caused the trigger to fire. In this case, Trigger.new contains all the new books that
are about to be inserted.
Book__c[] books = Trigger.new;

The next line in the code calls the method applyDiscount in the MyHelloWorld class. It passes in the array of new
books.
MyHelloWorld.applyDiscount(books);

You now have all the code that is needed to update the price of all books that get inserted. However, there is still one piece
of the puzzle missing. Unit tests are an important part of writing code and are required. In the next step, you will see why this
is so and you will be able to add a test class.

See Also:
Writing Your First Apex Class and Trigger
Adding an Apex Class
Adding a Test Class
Adding a Test Class
Prerequisites:

A Salesforce account in a sandbox Unlimited or Enterprise Edition organization, or an account in a Developer organization.
The HelloWorldTrigger Apex trigger.

In this step, you add a test class with one test method. You also run the test and verify code coverage. The test method exercises
and validates the code in the trigger and class. Also, it enables you to reach 100% code coverage for the trigger and class.
Note: Testing is an important part of the development process. Before you can deploy Apex or package it for the
Force.com AppExchange, the following must be true:

75% of your Apex code must be covered by unit tests, and all of those tests must complete successfully.
Note the following:

When deploying to a production organization, every unit test in your organization namespace is executed.
Calls to System.debug are not counted as part of Apex code coverage.
Test methods and test classes are not counted as part of Apex code coverage.
While only 75% of your Apex code must be covered by tests, your focus shouldn't be on the percentage of code
that is covered. Instead, you should make sure that every use case of your application is covered, including
positive and negative cases, as well as bulk and single record. This should lead to 75% or more of your code
being covered by unit tests.

Every trigger has some test coverage.


All classes and triggers compile successfully.

31

Introducing Apex

Writing Your First Apex Class and Trigger

1. Click Your Name > Setup > Develop > Apex Classes and click New.
2. In the class editor, add this test class definition, and then click Save.
@isTest
private class HelloWorldTestClass {
static testMethod void validateHelloWorld() {
Book__c b = new Book__c(Name='Behind the Cloud', Price__c=100);
System.debug('Price before inserting new book: ' + b.Price__c);
// Insert book
insert b;
// Retrieve the new book
b = [SELECT Price__c FROM Book__c WHERE Id =:b.Id];
System.debug('Price after trigger fired: ' + b.Price__c);
// Test that the trigger correctly updated the price
System.assertEquals(90, b.Price__c);
}
}

This class is defined using the @isTest annotation. Classes defined as such can only contain test methods. One advantage
to creating a separate class for testing as opposed to adding test methods to an existing class is that classes defined with
isTest don't count against your organization limit of 2 MB for all Apex code. You can also add the @isTest annotation
to individual methods. For more information, see IsTest Annotation on page 136 and Understanding Execution Governors
and Limits on page 222.
The method validateHelloWorld is defined as a testMethod. This means that if any changes are made to the
database, they are automatically rolled back when execution completes and you don't have to delete any test data created
in the test method.
First the test method creates a new book and inserts it into the database temporarily. The System.debug statement writes
the value of the price in the debug log.
Book__c b = new Book__c(Name='Behind the Cloud', Price__c=100);
System.debug('Price before inserting new book: ' + b.Price__c);
// Insert book
insert b;

Once the book is inserted, the code retrieves the newly inserted book, using the ID that was initially assigned to the book
when it was inserted, and then logs the new price, that the trigger modified:
// Retrieve the new book
b = [SELECT Price__c FROM Book__c WHERE Id =:b.Id];
System.debug('Price after trigger fired: ' + b.Price__c);

When the MyHelloWorld class runs, it updates the Price__c field and reduces its value by 10%. The following line is
the actual test, verifying that the method applyDiscount actually ran and produced the expected result:
// Test that the trigger correctly updated the price
System.assertEquals(90, b.Price__c);

3. Click Run Test in the class page to run all the test methods in this class. In this case, we have only one test method.
The Apex Test Result page appears after the test finishes execution. It contains the test result details such as the number
of test failures, code coverage information, and a link to a downloadable log file.

32

Introducing Apex

Writing Your First Apex Class and Trigger

4. Click Download and select to open the log file. You can find logging information about the trigger event, the call to the
applyDiscount class method, and the debug output of the price before and after the trigger.
Alternatively, you can use the Developer Console for debugging Apex code. See Developer Console in the Salesforce
online help.
5. You can also run the test through the Apex Test Execution page, which runs the test asynchronously, which means that
you don't have to wait for the test run to finish to get the test result, but you can perform other tasks in the user interface
while the test is still running and then visit this page later to check the test status.
a. Click Your Name > Setup > Develop > Apex Test Execution.
b. Click Run Tests.
c. Select the class HelloWorldTestClass, and then click Run.
After a test finishes running, you can:

Click the test to see result details; if a test fails, the first error message and the stack trace display.
Click View to see the source Apex code.

6. After the test execution completes, verify the amount of code coverage.
a. Click Your Name > Setup > Develop > Apex Classes.
b. Click Calculate your organization's code coverage to see the amount of code in your organization that is covered by
unit tests.
c. In the Code Coverage column, click 100% to see the lines of code covered by unit tests.
Take a look at the list of triggers by clicking Your Name > Setup > Develop > Apex Triggers. You'll see that the trigger
you wrote also has 100% of its code covered.
By now, you completed all the steps necessary for having some Apex code that has been tested and that runs in your development
environment. In the real world, after youve sufficiently tested your code and youre satisfied with it, you want to deploy the
code along with any other prerequisite components to a production organization. The next step will show you how to do this
for the code and custom object youve just created.

See Also:
Writing Your First Apex Class and Trigger
Adding an Apex Trigger
Deploying Components to Production
Deploying Components to Production
Prerequisites:

A Salesforce account in a sandbox Unlimited or Enterprise Edition organization.


The HelloWorldTestClass Apex test class.
A deployment connection between the sandbox and production organizations that allows inbound change sets to be received
by the production organization. See Change Sets Overview in the Salesforce online help.
Create and Upload Change Sets user permissions to create, edit, or upload outbound change sets.

In this step, you deploy the Apex code and the custom object you created previously to your production organization using
change sets.
This procedure doesn't apply to Developer organizations since change sets are available only in Unlimited, Enterprise, or
Database.com Edition organizations. If you have a Developer Edition account, you can use other deployment methods. See
Deploying Apex.

33

Introducing Apex

Writing Your First Apex Class and Trigger

1.
2.
3.
4.
5.
6.

Click Your Name > Setup > Deploy > Outbound Changesets.
If a splash page appears, click Continue.
In the Change Sets list, click New.
Enter a name for your change set, for example, HelloWorldChangeSet, and optionally a description. Click Save.
In the change set components section, click Add.
Select Apex Class from the component type drop-down list, then select the MyHelloWorld and the HelloWorldTestClass
classes from the list and click Add to Change Set.
7. Click View/Add Dependencies to add the dependent components.
8. Select the top checkbox to select all components. Click Add To Change Set.
9. In the change set detail section of the change set page, click Upload.
10. Select the target organization, in this case production, and click Upload.
11. After the change set upload completes, deploy it in your production organization.
a.
b.
c.
d.
e.

Log into your production organization.


Click Your Name > Setup > Deploy > Inbound Change Sets.
If a splash page appears, click Continue.
In the change sets awaiting deployment list, click your change set's name.
Click Deploy.

In this tutorial, you learned how to create a custom object, how to add an Apex trigger, class, and test class, and how to test
your code. Finally, you also learned how to upload the code and the custom object using Change Sets.

See Also:
Writing Your First Apex Class and Trigger
Adding a Test Class

34

Chapter 2
Language Constructs
In this chapter ...

Data Types
Variables
Expressions
Assignment Statements
Conditional (If-Else) Statements
Loops
SOQL and SOSL Queries
Locking Statements
Transaction Control
Exception Statements

Apex is a strongly typed, object-oriented, and case-insensitive programming


language. The Apex language constructs are building blocks that enable you to
write programs in Apex. Using those language constructs, you can declare variables
and constants of built-in data typesprimitives and sObjectsenumerations,
and custom data types based on system and user-provided Apex types. Apex
provides expressions, assignment, and conditional statements. Like other
programming languages, Apex provides exception handling and has different
types of loops. Unlike other languages, Apex has a special type of loop called
SOQL for loop, which allows for batching query results. Apex is integrated with
the databaseit allows you to write inline queries, perform record locking, and
control transactions.
The following language constructs form the base parts of Apex:

Data Types
Variables
Expressions
Assignment Statements
Conditional (If-Else) Statements
Loops
SOQL and SOSL Queries
Locking Statements
Transaction Control
Exception Statements

Apex is contained in either a trigger or a class. For more information, see Triggers
on page 83 and Classes, Objects, and Interfaces on page 106.

35

Language Constructs

Data Types

Data Types
In Apex, all variables and expressions have a data type that is one of the following:

A primitive, such as an Integer, Double, Long, Date, Datetime, String, ID, or Boolean (see Primitive Data Types on page
36)
An sObject, either as a generic sObject or as a specific sObject, such as an Account, Contact, or MyCustomObject__c
(see sObject Types on page 39)
A collection, including:
A list (or array) of primitives, sObjects, user defined objects, objects created from Apex classes, or collections (see Lists
on page 43)
A set of primitives (see Sets on page 48)
A map from a primitive to a primitive, sObject, or collection (see Maps on page 49)

A typed list of values, also known as an enum (see Enums on page 50)
Objects created from user-defined Apex classes (see Classes, Objects, and Interfaces on page 106)
Objects created from system supplied Apex classes (see Apex Classes on page 426)
Null (for the null constant, which can be assigned to any variable)

Methods can return values of any of the listed types, or return no value and be of type Void.
Type checking is strictly enforced at compile time. For example, the parser generates an error if an object field of type Integer
is assigned a value of type String. However, all compile-time exceptions are returned as specific fault codes, with the line
number and column of the error. For more information, see Debugging Apex on page 207.

Primitive Data Types


Apex uses the same primitive data types as the SOAP API. All primitive data types are passed by value.
All Apex variables, whether theyre class member variables or method variables, are initialized to null. Make sure that you
initialize your variables to appropriate values before using them. For example, initialize a Boolean variable to false.
Apex primitive data types include:
Data Type

Description

Blob

A collection of binary data stored as a single object. You can convert this datatype to String
or from String using the toString and valueOf methods, respectively. Blobs can be accepted
as Web service arguments, stored in a document (the body of a document is a Blob), or sent
as attachments. For more information, see Crypto Class on page 488.

Boolean

A value that can only be assigned true, false, or null. For example:
Boolean isWinner = true;

Date

A value that indicates a particular day. Unlike Datetime values, Date values contain no
information about time. Date values must always be created with a system static method.
You cannot manipulate a Date value, such as add days, merely by adding a number to a Date
variable. You must use the Date methods instead.

36

Language Constructs

Primitive Data Types

Data Type

Description

Datetime

A value that indicates a particular day and time, such as a timestamp. Datetime values must
always be created with a system static method.
You cannot manipulate a Datetime value, such as add minutes, merely by adding a number
to a Datetime variable. You must use the Datetime methods instead.

Decimal

A number that includes a decimal point. Decimal is an arbitrary precision number. Currency
fields are automatically assigned the type Decimal.
If you do not explicitly set the scale, that is, the number of decimal places, for a Decimal using
the setScale method, the scale is determined by the item from which the Decimal is created.

Double

If the Decimal is created as part of a query, the scale is based on the scale of the field
returned from the query.
If the Decimal is created from a String, the scale is the number of characters after the
decimal point of the String.
If the Decimal is created from a non-decimal number, the scale is determined by converting
the number to a String and then using the number of characters after the decimal point.

A 64-bit number that includes a decimal point. Doubles have a minimum value of -263 and
a maximum value of 263-1. For example:
Double d=3.14159;

Note that scientific notation (e) for Doubles is not supported.


ID

Any valid 18-character Force.com record identifier. For example:


ID id='00300000003T2PGAA0';

Note that if you set ID to a 15-character value, Apex automatically converts the value to its
18-character representation. All invalid ID values are rejected with a runtime exception.
Integer

A 32-bit number that does not include a decimal point. Integers have a minimum value of
-2,147,483,648 and a maximum value of 2,147,483,647. For example:
Integer i = 1;

Long

A 64-bit number that does not include a decimal point. Longs have a minimum value of -263
and a maximum value of 263-1. Use this datatype when you need a range of values wider than
those provided by Integer. For example:
Long l = 2147483648L;

String

Any set of characters surrounded by single quotes. For example,


String s = 'The quick brown fox jumped over the lazy dog.';

37

Language Constructs

Data Type

Primitive Data Types

Description
String size: Strings have no limit on the number of characters they can include. Instead, the
heap size limit is used to ensure that your Apex programs don't grow too large.
Empty Strings and Trailing Whitespace: sObject String field values follow the same rules
as in the SOAP API: they can never be empty (only null), and they can never include leading
and trailing whitespace. These conventions are necessary for database storage.
Conversely, Strings in Apex can be null or empty, and can include leading and trailing
whitespace (such as might be used to construct a message).
The Solution sObject field SolutionNote operates as a special type of String. If you have
HTML Solutions enabled, any HTML tags used in this field are verified before the object
is created or updated. If invalid HTML is entered, an error is thrown. Any JavaScript used
in this field is removed before the object is created or updated. In the following example,
when the Solution displays on a detail page, the SolutionNote field has H1 HTML formatting
applied to it:
trigger t on Solution (before insert) {
Trigger.new[0].SolutionNote ='<h1>hello</h1>';
}

In the following example, when the Solution displays on a detail page, the SolutionNote field
only contains HelloGoodbye:
trigger t2 on Solution (before insert) {
Trigger.new[0].SolutionNote =
'<javascript>Hello</javascript>Goodbye';
}

For more information, see What are HTML Solutions? in the online help.
Escape Sequences: All Strings in Apex use the same escape sequences as SOQL strings: \b
(backspace), \t (tab), \n (line feed), \f (form feed), \r (carriage return), \" (double quote),
\' (single quote), and \\ (backslash).
Comparison Operators: Unlike Java, Apex Strings support use of the comparison operators
==, !=, <, <=, >, and >=. Since Apex uses SOQL comparison semantics, results for Strings
are collated according to the context user's locale, and `are not case sensitive. For more
information, see Operators on page 56.
String Methods: As in Java, Strings can be manipulated with a number of standard methods.
See String Methods for information.
Apex classes and triggers saved (compiled) using API version 15.0 and higher produce a
runtime error if you assign a String value that is too long for the field.
Time

A value that indicates a particular time. Time values must always be created with a system
static method. See Time Methods on page 308.

In addition, two non-standard primitive data types cannot be used as variable or method types, but do appear in system static
methods:

38

Language Constructs

sObject Types

AnyType. The valueOf static method converts an sObject field of type AnyType to a standard primitive. AnyType is
used within the Force.com platform database exclusively for sObject fields in field history tracking tables.
Currency. The Currency.newInstance static method creates a literal of type Currency. This method is for use solely
within SOQL and SOSL WHERE clauses to filter against sObject currency fields. You cannot instantiate Currency in any
other type of Apex.

For more information on the AnyType data type, see Field Types in the Object Reference for Salesforce and Force.com.

sObject Types
In this developer's guide, the term sObject refers to any object that can be stored in the Force.com platform database. An
sObject variable represents a row of data and can only be declared in Apex using the SOAP API name of the object. For
example:
Account a = new Account();
MyCustomObject__c co = new MyCustomObject__c();

Similar to the SOAP API, Apex allows the use of the generic sObject abstract type to represent any object. The sObject data
type can be used in code that processes different types of sObjects.
The new operator still requires a concrete sObject type, so all instances are specific sObjects. For example:
sObject s = new Account();

You can also use casting between the generic sObject type and the specific sObject type. For example:
// Cast the generic variable s from the example above
// into a specific account and account variable a
Account a = (Account)s;
// The following generates a runtime error
Contact c = (Contact)s;

Because sObjects work like objects, you can also have the following:
Object obj = s;
// and
a = (Account)obj;

DML operations work on variables declared as the generic sObject data type as well as with regular sObjects.
sObject variables are initialized to null, but can be assigned a valid object reference with the new operator. For example:
Account a = new Account();

Developers can also specify initial field values with comma-separated name = value pairs when instantiating a new sObject.
For example:
Account a = new Account(name = 'Acme', billingcity = 'San Francisco');

For information on accessing existing sObjects from the Force.com platform database, see SOQL and SOSL Queries on page
70.

39

Language Constructs

sObject Types

Note: The ID of an sObject is a read-only value and can never be modified explicitly in Apex unless it is cleared
during a clone operation, or is assigned with a constructor. The Force.com platform assigns ID values automatically
when an object record is initially inserted to the database for the first time. For more information see Lists on page
43.

Custom Labels
Custom labels are not standard sObjects. You cannot create a new instance of a custom label. You can only access the value
of a custom label using system.label.label_name. For example:
String errorMsg = System.Label.generic_error;

For more information on custom labels, see Custom Labels Overview in the online help.
Accessing sObject Fields
As in Java, sObject fields can be accessed or changed with simple dot notation. For example:
Account a = new Account();
a.Name = 'Acme';
// Access the account name field and assign it 'Acme'

System generated fields, such as Created By or Last Modified Date, cannot be modified. If you try, the Apex runtime
engine generates an error. Additionally, formula field values and values for other fields that are read-only for the context user
cannot be changed.
If you use the generic sObject type, instead of a specific object such as Account, you can only retrieve the ID field. For example:
Account a = new Account(Name = 'Acme', BillingCity = 'San Francisco');
insert a;
sObject s = [SELECT Id, Name FROM Account WHERE Name = 'Acme' LIMIT 1];
// This is allowed
ID id = s.Id;
// The following lines result in errors when you try to save
String x = s.Name;
s.Id = [SELECT Id FROM Account WHERE Name = 'Acme' LIMIT 1];

Note: If your organization has enabled person accounts, you have two different kinds of accounts: business accounts
and person accounts. If your code creates a new account using name, a business account is created. If your code uses
LastName, a person account is created.
If you want to perform operations on an sObject, it is recommended that you first convert it into a specific object. For example:
Account a = new Account(Name = 'Acme', BillingCity = 'San Francisco');
insert a;
sObject s = [SELECT Id, Name FROM Account WHERE Name = 'Acme' LIMIT 1];
ID id = s.ID;
Account convertedAccount = (Account)s;
convertedAccount.name = 'Acme2';
update convertedAccount;
Contact sal = new Contact(FirstName = 'Sal', Account = convertedAccount);

40

Language Constructs

sObject Types

The following example shows how you can use SOSL over a set of records to determine their object types. Once you have
converted the generic sObject record into a Contact, Lead, or Account, you can modify its fields accordingly:
public class convertToCLA {
List<Contact> contacts;
List<Lead> leads;
List<Account> accounts;
public void convertType(Integer phoneNumber) {
List<List<sObject>> results = [FIND '4155557000'
IN Phone FIELDS
RETURNING Contact(Id, Phone, FirstName, LastName),
Lead(Id, Phone, FirstName, LastName), Account(Id, Phone, Name)];
sObject[] records = ((List<sObject>)results[0]);
if (!records.isEmpty()) {
for (Integer i = 0; i < records.size(); i++) {
sObject record = records[i];
if (record.getSObjectType() == Contact.sObjectType) {
contacts.add((Contact) record);
} else if (record.getSObjectType() == Lead.sObjectType){
leads.add((Lead) record);
} else if (record.getSObjectType() == Account.sObjectType) {
accounts.add((Account) record);
}
}
}
}
}

Accessing sObject Fields Through Relationships


sObject records represent relationships to other records with two fields: an ID and an address that points to a representation
of the associated sObject. For example, the Contact sObject has both an AccountId field of type ID, and an Account field
of type Account that points to the associated sObject record itself.
The ID field can be used to change the account with which the contact is associated, while the sObject reference field can be
used to access data from the account. The reference field is only populated as the result of a SOQL or SOSL query (see note
below).
For example, the following Apex code shows how an account and a contact can be associated with one another, and then how
the contact can be used to modify a field on the account:
Note: In order to provide the most complete example, this code uses some elements that are described later in this
guide:

For information on insert and update, see Insert Operation on page 270 and Update Operation on page 270.
For information on SOQL and SOSL, see SOQL and SOSL Queries on page 70.

Account a = new Account(Name = 'Acme');


insert a; // Inserting the record automatically assigns a
// value to its ID field
Contact c = new Contact(LastName = 'Weissman');
c.AccountId = a.Id;
// The new contact now points at the new account
insert c;
// A SOQL query accesses data for the inserted contact,
// including a populated c.account field

41

Language Constructs

sObject Types

c = [SELECT Account.Name FROM Contact WHERE Id = :c.Id];


// Now fields in both records can be changed through the contact
c.Account.Name = 'salesforce.com';
c.LastName = 'Roth';
// To update the database, the two types of records must be
// updated separately
update c;
// This only changes the contact's last name
update c.Account; // This updates the account name

Note: The expression c.Account.Name, as well as any other expression that traverses a relationship, displays slightly
different characteristics when it is read as a value than when it is modified:

When being read as a value, if c.Account is null, then c.Account.Name evaluates to null, but does not yield
a NullPointerException. This design allows developers to navigate multiple relationships without the tedium
of having to check for null values.
When being modified, if c.Account is null, then c.Account.Name does yield a NullPointerException.

In addition, the sObject field key can be used with insert, update, or upsert to resolve foreign keys by external ID. For
example:
Account refAcct = new Account(externalId__c = '12345');
Contact c = new Contact(Account = refAcct, LastName = 'Kay');
insert c;

This inserts a new contact with the AccountId equal to the account with the external_id equal to 12345. If there is no
such account, the insert fails.
Tip:
The following code is equivalent to the code above. However, because it uses a SOQL query, it is not as efficient. If
this code was called multiple times, it could reach the execution limit for the maximum number of SOQL queries.
For more information on execution limits, see Understanding Execution Governors and Limits on page 222.
Account refAcct = [SELECT Id FROM Account WHERE externalId__c='12345'];
Contact c = new Contact(Account = refAcct.Id);
insert c;

Validating sObjects and Fields


When Apex code is parsed and validated, all sObject and field references are validated against actual object and field names,
and a parse-time exception is thrown when an invalid name is used.
In addition, the Apex parser tracks the custom objects and fields that are used, both in the code's syntax as well as in embedded
SOQL and SOSL statements. The platform prevents users from making the following types of modifications when those
changes cause Apex code to become invalid:

Changing a field or object name


Converting from one data type to another
Deleting a field or object

42

Language Constructs

Collections

Making certain organization-wide changes, such as record sharing, field history tracking, or record types

Collections
Apex has the following types of collections:

Lists
Maps
Sets
Note: There is no limit on the number of items a collection can hold. However, there is a general limit on heap size.

Lists
A list is an ordered collection of typed primitives, sObjects, user-defined objects, Apex objects or collections that are distinguished
by their indices. For example, the following table is a visual representation of a list of Strings:
Index 0

Index 1

Index 2

Index 3

Index 4

Index 5

'Red'

'Orange'

'Yellow'

'Green'

'Blue'

'Purple'

The index position of the first element in a list is always 0.


Because lists can contain any collection, they can be nested within one another and become multidimensional. For example,
you can have a list of lists of sets of Integers. A list can only contain up to five levels of nested collections inside it.
To declare a list, use the List keyword followed by the primitive data, sObject, nested list, map, or set type within <> characters.
For example:
// Create an empty list of String
List<String> my_list = new List<String>();
// Create a nested list
List<List<Set<Integer>>> my_list_2 = new List<List<Set<Integer>>>();
// Create a list of account records from a SOQL query
List<Account> accs = [SELECT Id, Name FROM Account LIMIT 1000];

To access elements in a list, use the system methods provided by Apex. For example:
List<Integer> MyList = new List<Integer>(); // Define a new list
MyList.add(47);
// Adds a second element of value 47 to the end
// of the list
MyList.get(0);
// Retrieves the element at index 0
MyList.set(0, 1);
// Adds the integer 1 to the list at index 0
MyList.clear();
// Removes all elements from the list

For more information, including a complete list of all supported methods, see List Methods on page 309.

43

Language Constructs

Collections

Using Array Notation for One-Dimensional Lists of Primitives or sObjects


When using one-dimensional lists of primitives or sObjects, you can also use more traditional array notation to declare and
reference list elements. For example, you can declare a one-dimensional list of primitives or sObjects by following the data or
sObject type name with the [] characters:
String[] colors = new List<String>();

To reference an element of a one-dimensional list of primitives or sObjects, you can also follow the name of the list with the
element's index position in square brackets. For example:
colors[3] = 'Green';

All lists are initialized to null. Lists can be assigned values and allocated memory using literal notation. For example:
Example

Description
Defines an Integer list with no elements

List<Integer> ints = new Integer[0];

Defines an Account list with no elements


List<Account> accts = new Account[]{};

Defines an Integer list with memory allocated for six Integers


List<Integer> ints = new Integer[6];

List<Account> accts = new Account[]


{new Account(), null, new
Account()};

Defines an Account list with memory allocated for three


Accounts, including a new Account object in the first position,
null in the second position, and another new Account object
in the third position
Defines the Contact list with a new list

List<Contact> contacts = new List<Contact>


(otherList);

Lists of sObjects
Apex automatically generates IDs for each object in a list of sObjects when the list is successfully inserted or upserted into the
database with a data manipulation language (DML) statement. Consequently, a list of sObjects cannot be inserted or upserted
if it contains the same sObject more than once, even if it has a null ID. This situation would imply that two IDs would need
to be written to the same structure in memory, which is illegal.
For example, the insert statement in the following block of code generates a ListException because it tries to insert a
list with two references to the same sObject (a):
try {
// Create a list with two references to the same sObject element
Account a = new Account();

44

Language Constructs

Collections

Account[] accs = new Account[]{a, a};


// Attempt to insert it...
insert accs;
// Will not get here
System.assert(false);
} catch (ListException e) {
// But will get here
}

For more information on DML statements, see Apex Data Manipulation Language (DML) Operations on page 264.
You can use the generic sObject data type with lists. You can also create a generic instance of a list.
List Sorting
Using the List.sort method, you can sort lists of primitive data types, custom types (your Apex classes) that implement
the Comparable Interface, and sObjects (standard objects, custom objects, and SelectOption).
Sorting is in ascending order for primitive data types.
For custom types, the sort criteria and sort order depends on the implementation that you provide for the compareTo method
of the Comparable interface. For more information on implementing the Comparable Interface for your own classes, see
Comparable Interface.
For sObjects, sorting is in ascending order and uses a sequence of comparison steps outlined in the next section. However,
you can also implement a custom sort order for sObjects by wrapping your sObject in an Apex class and implementing the
Comparable Interface, as shown in Custom Sort Order of sObjects.
Default Sort Order of sObjects
The List.sort method sorts sObjects in ascending order and compares sObjects using an ordered sequence of steps that
specify the labels or fields used. The comparison starts with the first step in the sequence and ends when two sObjects are
sorted using specified labels or fields. The following is the comparison sequence used:
1. The label of the sObject type. For example, an Account sObject will appear before a Contact.
2. The Name field, if applicable. For example, if the list contains two accounts named A and B respectively, account A comes
before account B.
3. Standard fields, starting with the fields that come first in alphabetical order, except for the Id and Name fields. For example,
if two accounts have the same name, the first standard field used for sorting is AccountNumber.
4. Custom fields, starting with the fields that come first in alphabetical order. For example, suppose two accounts have the
same name and identical standard fields, and there are two custom fields, FieldA and FieldB, the value of FieldA is used
first for sorting.
Not all steps in this sequence are necessarily carried out. For example, if a list contains two sObjects of the same type and with
unique Name values, theyre sorted based on the Name field and sorting stops at step 2. Otherwise, if the names are identical
or the sObject doesnt have a Name field, sorting proceeds to step 3 to sort by standard fields.
For text fields, the sort algorithm uses the Unicode sort order. Also, empty fields precede non-empty fields in the sort order.
This is an example of sorting a list of Account sObjects. This example shows how the Name field is used to place the Acme
account ahead of the two sForce accounts in the list. Since there are two accounts named sForce, the Industry field is used to
sort these remaining accounts because the Industry field comes before the Site field in alphabetical order.
Account[] acctList = new List<Account>();
acctList.add( new Account(
Name='sForce',
Industry='Biotechnology',

45

Language Constructs

Collections

Site='Austin'));
acctList.add(new Account(
Name='sForce',
Industry='Agriculture',
Site='New York'));
acctList.add(new Account(
Name='Acme'));
System.debug(acctList);
acctList.sort();
System.assertEquals('Acme', acctList[0].Name);
System.assertEquals('sForce', acctList[1].Name);
System.assertEquals('Agriculture', acctList[1].Industry);
System.assertEquals('sForce', acctList[2].Name);
System.assertEquals('Biotechnology', acctList[2].Industry);
System.debug(acctList);

This example is similar to the previous one, except that it uses the Merchandise__c custom object. This example shows how
the Name field is used to place the Notebooks merchandise ahead of Pens in the list. Since there are two merchandise sObjects
with the Name field value of Pens, the Description field is used to sort these remaining merchandise items because the
Description field comes before the Price and Total_Inventory fields in alphabetical order.
Merchandise__c[] merchList = new List<Merchandise__c>();
merchList.add( new Merchandise__c(
Name='Pens',
Description__c='Red pens',
Price__c=2,
Total_Inventory__c=1000));
merchList.add( new Merchandise__c(
Name='Notebooks',
Description__c='Cool notebooks',
Price__c=3.50,
Total_Inventory__c=2000));
merchList.add( new Merchandise__c(
Name='Pens',
Description__c='Blue pens',
Price__c=1.75,
Total_Inventory__c=800));
System.debug(merchList);
merchList.sort();
System.assertEquals('Notebooks', merchList[0].Name);
System.assertEquals('Pens', merchList[1].Name);
System.assertEquals('Blue pens', merchList[1].Description__c);
System.assertEquals('Pens', merchList[2].Name);
System.assertEquals('Red pens', merchList[2].Description__c);
System.debug(merchList);

Custom Sort Order of sObjects


To implement a custom sort order for sObjects in lists, create a wrapper class for the sObject and implement the Comparable
Interface. The wrapper class contains the sObject in question and implements the compareTo method, in which you specify
the sort logic.
This example shows how to create a wrapper class for Opportunity. The implementation of the compareTo method in this
class compares two opportunities based on the Amount fieldthe class member variable contained in this instance, and the
opportunity object passed into the method.
global class OpportunityWrapper implements Comparable {
public Opportunity oppy;
// Constructor

46

Language Constructs

Collections

public OpportunityWrapper(Opportunity op) {


oppy = op;
}
// Compare opportunities based on the opportunity amount.
global Integer compareTo(Object compareTo) {
// Cast argument to OpportunityWrapper
OpportunityWrapper compareToOppy = (OpportunityWrapper)compareTo;
// The return value of 0 indicates that both elements are equal.
Integer returnValue = 0;
if (oppy.Amount > compareToOppy.oppy.Amount) {
// Set return value to a positive value.
returnValue = 1;
} else if (oppy.Amount < compareToOppy.oppy.Amount) {
// Set return value to a negative value.
returnValue = -1;
}
return returnValue;
}
}

This example provides a test for the OpportunityWrapper class. It sorts a list of OpportunityWrapper objects and verifies
that the list elements are sorted by the opportunity amount.
@isTest
private class OpportunityWrapperTest {
static testmethod void test1() {
// Add the opportunity wrapper objects to a list.
OpportunityWrapper[] oppyList = new List<OpportunityWrapper>();
Date closeDate = Date.today().addDays(10);
oppyList.add( new OpportunityWrapper(new Opportunity(
Name='Edge Installation',
CloseDate=closeDate,
StageName='Prospecting',
Amount=50000)));
oppyList.add( new OpportunityWrapper(new Opportunity(
Name='United Oil Installations',
CloseDate=closeDate,
StageName='Needs Analysis',
Amount=100000)));
oppyList.add( new OpportunityWrapper(new Opportunity(
Name='Grand Hotels SLA',
CloseDate=closeDate,
StageName='Prospecting',
Amount=25000)));
// Sort the wrapper objects using the implementation of the
// compareTo method.
oppyList.sort();
// Verify the sort order
System.assertEquals('Grand Hotels SLA', oppyList[0].oppy.Name);
System.assertEquals(25000, oppyList[0].oppy.Amount);
System.assertEquals('Edge Installation', oppyList[1].oppy.Name);
System.assertEquals(50000, oppyList[1].oppy.Amount);
System.assertEquals('United Oil Installations', oppyList[2].oppy.Name);
System.assertEquals(100000, oppyList[2].oppy.Amount);
// Write the sorted list contents to the debug log.
System.debug(oppyList);
}
}

47

Language Constructs

Collections

Sets
A set is an unordered collection of primitives or sObjects that do not contain any duplicate elements. For example, the following
table represents a set of String, that uses city names:
'San Francisco'

'New York'

'Paris'

'Tokyo'

To declare a set, use the Set keyword followed by the primitive data type name within <> characters. For example:
new Set<String>()

The following are ways to declare and populate a set:


Set<String> s1 = new Set<String>{'a', 'b + c'}; // Defines a new set with two elements
Set<String> s2 = new Set<String>(s1); // Defines a new set that contains the
// elements of the set created in the previous step

To access elements in a set, use the system methods provided by Apex. For example:
Set<Integer> s = new Set<Integer>();
s.add(1);
System.assert(s.contains(1));
s.remove(1);

//
//
//
//

Define
Add an
Assert
Remove

a new set
element to the set
that the set contains an element
the element from the set

Uniqueness of sObjects is determined by comparing fields. For example, if you try to add two accounts with the same name
to a set, only one is added.
// Create two accounts, a1 and a2
Account a1 = new account(name='MyAccount');
Account a2 = new account(name='MyAccount');
// Add both accounts to the new set
Set<Account> accountSet = new Set<Account>{a1, a2};
// Verify that the set only contains one item
System.assertEquals(accountSet.size(), 1);

However, if you add a description to one of the accounts, it is considered unique:


// Create two accounts, a1 and a2, and add a description to a2
Account a1 = new account(name='MyAccount');
Account a2 = new account(name='MyAccount', description='My test account');
// Add both accounts to the new set
Set<Account> accountSet = new Set<Account>{a1, a2};
// Verify that the set contains two items
System.assertEquals(accountSet.size(), 2);

For more information, including a complete list of all supported set system methods, see Set Methods on page 320.
Note the following limitations on sets:

Unlike Java, Apex developers do not need to reference the algorithm that is used to implement a set in their declarations
(for example, HashSet or TreeSet). Apex uses a hash structure for all sets.

48

Language Constructs

Collections

A set is an unordered collection. Do not rely on the order in which set results are returned. The order of objects returned
by sets may change without warning.

Maps
A map is a collection of key-value pairs where each unique key maps to a single value. Keys can be any primitive data type,
while values can be a primitive, sObject, collection type or an Apex object. For example, the following table represents a map
of countries and currencies:
Country (Key)

'United States'

'Japan'

'France'

'England'

'India'

Currency (Value)

'Dollar'

'Yen'

'Euro'

'Pound'

'Rupee'

Similar to lists, map values can contain any collection, and can be nested within one another. For example, you can have a
map of Integers to maps, which, in turn, map Strings to lists. A map can only contain up to five levels of nested collections
inside it.
To declare a map, use the Map keyword followed by the data types of the key and the value within <> characters. For example:
Map<String, String> country_currencies = new Map<String, String>();
Map<ID, Set<String>> m = new Map<ID, Set<String>>();
Map<ID, Map<ID, Account[]>> m2 = new Map<ID, Map<ID, Account[]>>();

You can use the generic sObject data type with maps. You can also create a generic instance of a map.
As with lists, you can populate map key-value pairs when the map is declared by using curly brace ({}) syntax. Within the
curly braces, specify the key first, then specify the value for that key using =>. For example:
Map<String, String> MyStrings = new Map<String, String>{'a' => 'b', 'c' => 'd'.toUpperCase()};
Account[] accs = new Account[5]; // Account[] is synonymous with List<Account>
Map<Integer, List<Account>> m4 = new Map<Integer, List<Account>>{1 => accs};

In the first example, the value for the key a is b, and the value for the key c is d. In the second, the key 1 has the value of the
list accs.
To access elements in a map, use the system methods provided by Apex. For example:
Account myAcct = new Account();
//Define a new account
Map<Integer, Account> m = new Map<Integer, Account>(); // Define a new map
m.put(1, myAcct);
// Insert a new key-value pair in the map
System.assert(!m.containsKey(3)); // Assert that the map contains a key
Account a = m.get(1);
// Retrieve a value, given a particular key
Set<Integer> s = m.keySet();
// Return a set that contains all of the keys in the map

For more information, including a complete list of all supported map system methods, see Map Methods on page 316.
Note the following considerations on maps:

Unlike Java, Apex developers do not need to reference the algorithm that is used to implement a map in their declarations
(for example, HashMap or TreeMap). Apex uses a hash structure for all maps.
Do not rely on the order in which map results are returned. The order of objects returned by maps may change without
warning. Always access map elements by key.
A map key can hold the null value.

49

Language Constructs

Enums

Maps from SObject Arrays


Maps from an ID or String data type to an sObject can be initialized from a list of sObjects. The IDs of the objects (which
must be non-null and distinct) are used as the keys. One common usage of this map type is for in-memory joins between
two tables. For instance, this example loads a map of IDs and Contacts:
Map<ID, Contact> m = new Map<ID, Contact>([SELECT Id, LastName FROM Contact]);

In the example, the SOQL query returns a list of contacts with their Id and LastName fields. The new operator uses the list
to create a map. For more information, see SOQL and SOSL Queries on page 70.
Iterating Collections
Collections can consist of lists, sets, or maps. Modifying a collection's elements while iterating through that collection is not
supported and causes an error. Do not directly add or remove elements while iterating through the collection that includes
them.
Adding Elements During Iteration
To add elements while iterating a list, set or map, keep the new elements in a temporary list, set, or map and add them to the
original after you finish iterating the collection.
Removing Elements During Iteration
To remove elements while iterating a list, create a new list, then copy the elements you wish to keep. Alternatively, add the
elements you wish to remove to a temporary list and remove them after you finish iterating the collection.
Note:
The List.remove method performs linearly. Using it to remove elements has time and resource implications.
To remove elements while iterating a map or set, keep the keys you wish to remove in a temporary list, then remove them
after you finish iterating the collection.

Enums
An enum is an abstract data type with values that each take on exactly one of a finite set of identifiers that you specify. Enums
are typically used to define a set of possible values that do not otherwise have a numerical order, such as the suit of a card, or
a particular season of the year. Although each value corresponds to a distinct integer value, the enum hides this implementation
so that you do not inadvertently misuse the values, such as using them to perform arithmetic. After you create an enum,
variables, method arguments, and return types can be declared of that type.
Note: Unlike Java, the enum type itself has no constructor syntax.

To define an enum, use the enum keyword in your declaration and use curly braces to demarcate the list of possible values.
For example, the following code creates an enum called Season:
public enum Season {WINTER, SPRING, SUMMER, FALL}

50

Language Constructs

Enums

By creating the enum Season, you have also created a new data type called Season. You can use this new data type as you
might any other data type. For example:
Season e = Season.WINTER;
Season m(Integer x, Season e) {
If (e == Season.SUMMER) return e;
//...
}

You can also define a class as an enum. Note that when you create an enum class you do not use the class keyword in the
definition.
public enum MyEnumClass { X, Y }

You can use an enum in any place you can use another data type name. If you define a variable whose type is an enum, any
object you assign to it must be an instance of that enum class.
Any webService methods can use enum types as part of their signature. When this occurs, the associated WSDL file includes
definitions for the enum and its values, which can then be used by the API client.
Apex provides the following system-defined enums:

System.StatusCode

This enum corresponds to the API error code that is exposed in the WSDL document for all API operations. For example:
StatusCode.CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY
StatusCode.INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY

The full list of status codes is available in the WSDL file for your organization. For more information about accessing the
WSDL file for your organization, see Downloading Salesforce WSDLs and Client Authentication Certificates in the
Salesforce online help.

System.XmlTag:

This enum returns a list of XML tags used for parsing the result XML from a webService method. For more information,
see XmlStreamReader Class on page 496.

System.ApplicationReadWriteMode: This enum indicates if an organization is in 5 Minute Upgrade read-only mode


during Salesforce upgrades and downtimes. For more information, see Using the System.ApplicationReadWriteMode

Enum on page 408.

System.LoggingLevel:

This enum is used with the system.debug method, to specify the log level for all debug calls. For more information,
see System Methods on page 400.

System.RoundingMode:

This enum is used by methods that perform mathematical operations to specify the rounding behavior for the operation,
such as the Decimal divide method and the Double round method. For more information, see Rounding Mode on
page 299.

System.SoapType:

This enum is returned by the field describe result getSoapType method. For more informations, see Schema.SOAPType
Enum Values on page 343.

51

Language Constructs

Understanding Rules of Conversion

System.DisplayType:

This enum is returned by the field describe result getType method. For more information, see Schema.DisplayType
Enum Values on page 340.

System.JSONToken:

This enum is used for parsing JSON content. For more information, see System.JSONToken Enum on page 386.

ApexPages.Severity:

This enum specifies the severity of a Visualforce message. For more information, see ApexPages.Severity Enum on page
458.

Dom.XmlNodeType:

This enum specifies the node type in a DOM document. For more information, see Node Types on page 505.
Note: System-defined enums cannot be used in Web service methods.

All enum values, including system enums, have common methods associated with them. For more information, see Enum
Methods on page 323.
You cannot add user-defined methods to enum values.

Understanding Rules of Conversion


In general, Apex requires you to explicitly convert one data type to another. For example, a variable of the Integer data type
cannot be implicitly converted to a String. You must use the string.format method. However, a few data types can be
implicitly converted, without using a method.
Numbers form a hierarchy of types. Variables of lower numeric types can always be assigned to higher types without explicit
conversion. The following is the hierarchy for numbers, from lowest to highest:
1.
2.
3.
4.

Integer
Long
Double
Decimal
Note: Once a value has been passed from a number of a lower type to a number of a higher type, the value is converted
to the higher type of number.

Note that the hierarchy and implicit conversion is unlike the Java hierarchy of numbers, where the base interface number is
used and implicit object conversion is never allowed.
In addition to numbers, other data types can be implicitly converted. The following rules apply:

IDs can always be assigned to Strings.


Strings can be assigned to IDs. However, at runtime, the value is checked to ensure that it is a legitimate ID. If it is not,
a runtime exception is thrown.
The instanceOf keyword can always be used to test whether a string is an ID.

52

Language Constructs

Variables

Additional Considerations for Data Types


Data Types of Numeric Values
Numeric values represent Integer values unless they are appended with L for a Long or with .0 for a Double or Decimal.
For example, the expression Long d = 123; declares a Long variable named d and assigns it to an Integer numeric
value (123), which is implicitly converted to a Long. The Integer value on the right hand side is within the range for
Integers and the assignment succeeds. However, if the numeric value on the right hand side exceeds the maximum value
for an Integer, you get a compilation error. In this case, the solution is to append L to the numeric value so that it
represents a Long value which has a wider range, as shown in this example: Long d = 2147483648L;.
Overflow of Data Type Values
Arithmetic computations that produce values larger than the maximum value of the current type are said to overflow.
For example, Integer i = 2147483647 + 1; yields a value of 2147483648 because 2147483647 is the maximum
value for an Integer, so adding one to it wraps the value around to the minimum negative value for Integers, 2147483648.
If arithmetic computations generate results larger than the maximum value for the current type, the end result will be
incorrect because the computed values that are larger than the maximum will overflow. For example, the expression
Long MillsPerYear = 365 * 24 * 60 * 60 * 1000; results in an incorrect result because the products of
Integers on the right hand side are larger than the maximum Integer value and they overflow. As a result, the final
product isn't the expected one. You can avoid this by ensuring that the type of numeric values or variables you are using
in arithmetic operations are large enough to hold the results. In this example, append L to numeric values to make them
Long so the intermediate products will be Long as well and no overflow occurs. The following example shows how to
correctly compute the amount of milliseconds in a year by multiplying Long numeric values.
Long MillsPerYear = 365L * 24L * 60L * 60L * 1000L;
Long ExpectedValue = 31536000000L;
System.assertEquals(MillsPerYear, ExpectedValue);

Loss of Fractions in Divisions


When dividing numeric Integer or Long values, the fractional portion of the result, if any, is removed before performing
any implicit conversions to a Double or Decimal. For example, Double d = 5/3; returns 1.0 because the actual result
(1.666...) is an Integer and is rounded to 1 before being implicitly converted to a Double. To preserve the fractional
value, ensure that you are using Double or Decimal numeric values in the division. For example, Double d = 5.0/3.0;
returns 1.6666666666666667 because 5.0 and 3.0 represent Double values, which results in the quotient being a Double
as well and no fractional value is lost.

Variables
Local variables are declared with Java-style syntax. For example:
Integer i = 0;
String str;
Account a;
Account[] accts;
Set<String> s;
Map<ID, Account> m;

As with Java, multiple variables can be declared and initialized in a single statement, using comma separation. For example:
Integer i, j, k;

53

Language Constructs

Case Sensitivity

All variables allow null as a value and are initialized to null if they are not assigned another value. For instance, in the
following example, i, and k are assigned values, while j is set to null because it is not assigned:
Integer i = 0, j, k = 1;

Variables can be defined at any point in a block, and take on scope from that point forward. Sub-blocks cannot redefine a
variable name that has already been used in a parent block, but parallel blocks can reuse a variable name. For example:
Integer i;
{
// Integer i;
}

This declaration is not allowed

for (Integer j = 0; j < 10; j++);


for (Integer j = 0; j < 10; j++);

Case Sensitivity
To avoid confusion with case-insensitive SOQL and SOSL queries, Apex is also case-insensitive. This means:

Variable and method names are case insensitive. For example:


Integer I;
//Integer i;

This would be an error.

References to object and field names are case insensitive. For example:
Account a1;
ACCOUNT a2;

SOQL and SOSL statements are case insensitive. For example:


Account[] accts = [sELect ID From ACCouNT where nAme = 'fred'];

Also note that Apex uses the same filtering semantics as SOQL, which is the basis for comparisons in the SOAP API and
the Salesforce user interface. The use of these semantics can lead to some interesting behavior. For example, if an end user
generates a report based on a filter for values that come before 'm' in the alphabet (that is, values < 'm'), null fields are returned
in the result. The rationale for this behavior is that users typically think of a field without a value as just a space character,
rather than its actual null value. Consequently, in Apex, the following expressions all evaluate to true:
String s;
System.assert('a' == 'A');
System.assert(s < 'b');
System.assert(!(s > 'b'));

Note: Although s < 'b' evaluates to true in the example above, 'b.'compareTo(s) generates an error because
you are trying to compare a letter to a null value.

54

Language Constructs

Constants

Constants
Constants can be defined using the final keyword, which means that the variable can be assigned at most once, either in
the declaration itself, or with a static initializer method if the constant is defined in a class. For example:
public class myCls {
static final Integer PRIVATE_INT_CONST;
static final Integer PRIVATE_INT_CONST2 = 200;
public static Integer calculate() {
return 2 + 7;
}
static {
PRIVATE_INT_CONST = calculate();
}
}

For more information, see Using the final Keyword on page 128.

Expressions
An expression is a construct made up of variables, operators, and method invocations that evaluates to a single value. This
section provides an overview of expressions in Apex and contains the following:

Understanding Expressions
Understanding Expression Operators
Understanding Operator Precedence
Extending sObject and List Expressions
Using Comments

Understanding Expressions
An expression is a construct made up of variables, operators, and method invocations that evaluates to a single value. In Apex,
an expression is always one of the following types:

A literal expression. For example:


1 + 1

A new sObject, Apex object, list, set, or map. For example:


new
new
new
new
new
new
new

Account(<field_initializers>)
Integer[<n>]
Account[]{<elements>}
List<Account>()
Set<String>{}
Map<String, Integer>()
myRenamingClass(string oldName, string newName)

55

Language Constructs

Understanding Expression Operators

Any value that can act as the left-hand of an assignment operator (L-values), including variables, one-dimensional list
positions, and most sObject or Apex object field references. For example:

Integer i
myList[3]
myContact.name
myRenamingClass.oldName

Any sObject field reference that is not an L-value, including:

The ID of an sObject in a list (see Lists)


A set of child records associated with an sObject (for example, the set of contacts associated with a particular account).
This type of expression yields a query result, much like SOQL and SOSL queries.
A SOQL or SOSL query surrounded by square brackets, allowing for on-the-fly evaluation in Apex. For example:

Account[] aa = [SELECT Id, Name FROM Account WHERE Name ='Acme'];


Integer i = [SELECT COUNT() FROM Contact WHERE LastName ='Weissman'];
List<List<SObject>> searchList = [FIND 'map*' IN ALL FIELDS RETURNING Account (Id, Name),
Contact, Opportunity, Lead];

For information, see SOQL and SOSL Queries on page 70.


A static or instance method invocation. For example:

System.assert(true)
myRenamingClass.replaceNames()
changePoint(new Point(x, y));

Understanding Expression Operators


Expressions can also be joined to one another with operators to create compound expressions. Apex supports the following
operators:
Operator

Syntax

Description

x = y

Assignment operator (Right associative). Assigns the value of y to the L-value


x. Note that the data type of x must match the data type of y, and cannot be
null.

+=

x += y

Addition assignment operator (Right associative). Adds the value of y to


the original value of x and then reassigns the new value to x. See + for
additional information. x and y cannot be null.

*=

x *= y

Multiplication assignment operator (Right associative). Multiplies the value


of y with the original value of x and then reassigns the new value to x. Note
that x and y must be Integers or Doubles, or a combination. x and y cannot
be null.

-=

x -= y

Subtraction assignment operator (Right associative). Subtracts the value of


y from the original value of x and then reassigns the new value to x. Note
that x and y must be Integers or Doubles, or a combination. x and y cannot
be null.

56

Language Constructs

Understanding Expression Operators

Operator

Syntax

Description

/=

x /= y

Division assignment operator (Right associative). Divides the original value


of x with the value of y and then reassigns the new value to x. Note that x
and y must be Integers or Doubles, or a combination. x and y cannot be
null.

|=

x |= y

OR assignment operator (Right associative). If x, a Boolean, and y, a Boolean,


are both false, then x remains false. Otherwise, x is assigned the value of true.
Note:

&=

x &= y

This operator exhibits short-circuiting behavior, which means y is


evaluated only if x is false.
x and y cannot be null.

AND assignment operator (Right associative). If x, a Boolean, and y, a


Boolean, are both true, then x remains true. Otherwise, x is assigned the value
of false.
Note:

This operator exhibits short-circuiting behavior, which means y is


evaluated only if x is true.
x and y cannot be null.

<<=

x <<= y

Bitwise shift left assignment operator. Shifts each bit in x to the left by y
bits so that the high order bits are lost, and the new right bits are set to 0.
This value is then reassigned to x.

>>=

x >>= y

Bitwise shift right signed assignment operator. Shifts each bit in x to the
right by y bits so that the low order bits are lost, and the new left bits are set
to 0 for positive values of y and 1 for negative values of y. This value is then
reassigned to x.

>>>=

x >>>= y

Bitwise shift right unsigned assignment operator. Shifts each bit in x to the
right by y bits so that the low order bits are lost, and the new left bits are set
to 0 for all values of y. This value is then reassigned to x.

? :

x ? y : z

Ternary operator (Right associative). This operator acts as a short-hand for


if-then-else statements. If x, a Boolean, is true, y is the result. Otherwise z
is the result. Note that x cannot be null.

&&

x && y

AND logical operator (Left associative). If x, a Boolean, and y, a Boolean,


are both true, then the expression evaluates to true. Otherwise the expression
evaluates to false.
Note:

&& has precedence over ||

This operator exhibits short-circuiting behavior, which means y is


evaluated only if x is true.
x and y cannot be null.

57

Language Constructs

Understanding Expression Operators

Operator

Syntax

Description

||

x || y

OR logical operator (Left associative). If x, a Boolean, and y, a Boolean, are


both false, then the expression evaluates to false. Otherwise the expression
evaluates to true.
Note:

==

x == y

&& has precedence over ||

This operator exhibits short-circuiting behavior, which means y is


evaluated only if x is false.
x and y cannot be null.

Equality operator. If the value of x equals the value of y, the expression


evaluates to true. Otherwise, the expression evaluates to false.
Note:

Unlike Java, == in Apex compares object value equality, not reference


equality. Consequently:
String comparison using == is case insensitive
ID comparison using == is case sensitive, and does not distinguish
between 15-character and 18-character formats

===

x === y

For sObjects and sObject arrays, == performs a deep check of all sObject
field values before returning its result.
For records, every field must have the same value for == to evaluate to
true.
x or y can be the literal null.
The comparison of any two values can never result in null.
SOQL and SOSL use = for their equality operator, and not ==. Although
Apex and SOQL and SOSL are strongly linked, this unfortunate syntax
discrepancy exists because most modern languages use = for assignment
and == for equality. The designers of Apex deemed it more valuable to
maintain this paradigm than to force developers to learn a new assignment
operator. The result is that Apex developers must use == for equality tests
in the main body of the Apex code, and = for equality in SOQL and SOSL
queries.

Exact equality operator. If x and y reference the exact same location in


memory, the expression evaluates to true. Otherwise, the expression evaluates
to false. Note that this operator only works for sObjects or collections (such
as a Map or list). For an Apex object (such as an Exception or instantiation
of a class) the exact equality operator is the same as the equality operator.

58

Language Constructs

Understanding Expression Operators

Operator

Syntax

Description

<

x < y

Less than operator. If x is less than y, the expression evaluates to true.


Otherwise, the expression evaluates to false.
Note:

>

x > y

Unlike other database stored procedures, Apex does not support tri-state
Boolean logic, and the comparison of any two values can never result in
null.
If x or y equal null and are Integers, Doubles, Dates, or Datetimes, the
expression is false.
A non-null String or ID value is always greater than a null value.
If x and y are IDs, they must reference the same type of object. Otherwise,
a runtime error results.
If x or y is an ID and the other value is a String, the String value is
validated and treated as an ID.
x and y cannot be Booleans.
The comparison of two strings is performed according to the locale of the
context user.

Greater than operator. If x is greater than y, the expression evaluates to true.


Otherwise, the expression evaluates to false.
Note:

<=

x <= y

The comparison of any two values can never result in null.


If x or y equal null and are Integers, Doubles, Dates, or Datetimes, the
expression is false.
A non-null String or ID value is always greater than a null value.
If x and y are IDs, they must reference the same type of object. Otherwise,
a runtime error results.
If x or y is an ID and the other value is a String, the String value is
validated and treated as an ID.
x and y cannot be Booleans.
The comparison of two strings is performed according to the locale of the
context user.

Less than or equal to operator. If x is less than or equal to y, the expression


evaluates to true. Otherwise, the expression evaluates to false.
Note:

The comparison of any two values can never result in null.


If x or y equal null and are Integers, Doubles, Dates, or Datetimes, the
expression is false.
A non-null String or ID value is always greater than a null value.
If x and y are IDs, they must reference the same type of object. Otherwise,
a runtime error results.

59

Language Constructs

Operator

Understanding Expression Operators

Syntax

Description

>=

x >= y

If x or y is an ID and the other value is a String, the String value is


validated and treated as an ID.
x and y cannot be Booleans.
The comparison of two strings is performed according to the locale of the
context user.

Greater than or equal to operator. If x is greater than or equal to y, the


expression evaluates to true. Otherwise, the expression evaluates to false.
Note:

!=

x != y

The comparison of any two values can never result in null.


If x or y equal null and are Integers, Doubles, Dates, or Datetimes, the
expression is false.
A non-null String or ID value is always greater than a null value.
If x and y are IDs, they must reference the same type of object. Otherwise,
a runtime error results.
If x or y is an ID and the other value is a String, the String value is
validated and treated as an ID.
x and y cannot be Booleans.
The comparison of two strings is performed according to the locale of the
context user.

Inequality operator. If the value of x does not equal the value of y, the
expression evaluates to true. Otherwise, the expression evaluates to false.
Note:

Unlike Java, != in Apex compares object value equality, not reference


equality.
For sObjects and sObject arrays, != performs a deep check of all sObject
field values before returning its result.
For records, != evaluates to true if the records have different values for
any field.
x or y can be the literal null.
The comparison of any two values can never result in null.

!==

x !== y

Exact inequality operator. If x and y do not reference the exact same location
in memory, the expression evaluates to true. Otherwise, the expression evaluates
to false. Note that this operator only works for sObjects, collections (such as
a Map or list), or an Apex object (such as an Exception or instantiation of a
class).

x + y

Addition operator. Adds the value of x to the value of y according to the


following rules:
If x and y are Integers or Doubles, adds the value of x to the value of y.
If a Double is used, the result is a Double.

60

Language Constructs

Operator

Understanding Expression Operators

Syntax

Description

If x is a Date and y is an Integer, returns a new Date that is incremented


by the specified number of days.
If x is a Datetime and y is an Integer or Double, returns a new Date that
is incremented by the specified number of days, with the fractional portion
corresponding to a portion of a day.
If x is a String and y is a String or any other type of non-null argument,
concatenates y to the end of x.

x - y

Subtraction operator. Subtracts the value of y from the value of x according


to the following rules:
If x and y are Integers or Doubles, subtracts the value of x from the value
of y. If a Double is used, the result is a Double.
If x is a Date and y is an Integer, returns a new Date that is decremented
by the specified number of days.
If x is a Datetime and y is an Integer or Double, returns a new Date that
is decremented by the specified number of days, with the fractional portion
corresponding to a portion of a day.

x * y

Multiplication operator. Multiplies x, an Integer or Double, with y, another


Integer or Double. Note that if a double is used, the result is a Double.

x / y

Division operator. Divides x, an Integer or Double, by y, another Integer or


Double. Note that if a double is used, the result is a Double.

!x

Logical complement operator. Inverts the value of a Boolean, so that true


becomes false, and false becomes true.

-x

Unary negation operator. Multiplies the value of x, an Integer or Double,


by -1. Note that the positive equivalent + is also syntactically valid, but does
not have a mathematical effect.

++

x++

Increment operator. Adds 1 to the value of x, an Integer or Double. If prefixed


(++x), the increment occurs before the rest of the statement is executed. If
postfixed (x--), the increment occurs after the rest of the statement is
executed.

++x

--

x---x

Decrement operator. Subtracts 1 from the value of x, an Integer or Double.


If prefixed (--x), the decrement occurs before the rest of the statement is
executed. If postfixed (x--), the decrement occurs after the rest of the
statement is executed.

&

x & y

Bitwise AND operator. ANDs each bit in x with the corresponding bit in y
so that the result bit is set to 1 if both of the bits are set to 1. This operator
is not valid for types Long or Integer.

x | y

Bitwise OR operator. ORs each bit in x with the corresponding bit in y so


that the result bit is set to 1 if at least one of the bits is set to 1. This operator
is not valid for types Long or Integer.

61

Language Constructs

Understanding Operator Precedence

Operator

Syntax

Description

x ^ y

Bitwise exclusive OR operator. Exclusive ORs each bit in x with the


corresponding bit in y so that the result bit is set to 1 if exactly one of the bits
is set to 1 and the other bit is set to 0.

^=

x ^= y

Bitwise exclusive OR operator. Exclusive ORs each bit in x with the


corresponding bit in y so that the result bit is set to 1 if exactly one of the bits
is set to 1 and the other bit is set to 0.

<<

x << y

Bitwise shift left operator. Shifts each bit in x to the left by y bits so that the
high order bits are lost, and the new right bits are set to 0.

>>

x >> y

Bitwise shift right signed operator. Shifts each bit in x to the right by y bits
so that the low order bits are lost, and the new left bits are set to 0 for positive
values of y and 1 for negative values of y.

>>>

x >>> y

Bitwise shift right unsigned operator. Shifts each bit in x to the right by y
bits so that the low order bits are lost, and the new left bits are set to 0 for all
values of y.

()

(x)

Parentheses. Elevates the precedence of an expression x so that it is evaluated


first in a compound expression.

Understanding Operator Precedence


Apex uses the following operator precedence rules:
Precedence

Operators

Description

{} () ++ --

Grouping and prefix increments and decrements

! -x +x (type) new

Unary negation, type cast and object creation

* /

Multiplication and division

+ -

Addition and subtraction

< <= > >= instanceof

Greater-than and less-than comparisons, reference


tests

== !=

Comparisons: equal and not-equal

&&

Logical AND

||

Logical OR

= += -= *= /= &=

Assignment operators

62

Language Constructs

Extending sObject and List Expressions

Extending sObject and List Expressions


As in Java, sObject and list expressions can be extended with method references and list expressions, respectively, to form new
expressions.
In the following example, a new variable containing the length of the new account name is assigned to acctNameLength.
Integer acctNameLength = new Account[]{new Account(Name='Acme')}[0].Name.length();

In the above, new Account[] generates a list.


The list is populated by the SOQL statement {new Account(name='Acme')}.
Item 0, the first item in the list, is then accessed by the next part of the string [0].
The name of the sObject in the list is accessed, followed by the method returning the length name.length().
In the following example, a name that has been shifted to lower case is returned.
String nameChange = [SELECT Name FROM Account][0].Name.toLowerCase();

Using Comments
Both single and multiline comments are supported in Apex code:

To create a single line comment, use //. All characters on the same line to the right of the // are ignored by the parser.
For example:
Integer i = 1; // This comment is ignored by the parser

To create a multiline comment, use /* and */ to demarcate the beginning and end of the comment block. For example:
Integer i = 1; /* This comment can wrap over multiple
lines without getting interpreted by the
parser. */

Assignment Statements
An assignment statement is any statement that places a value into a variable, generally in one of the following two forms:
[LValue] = [new_value_expression];
[LValue] = [[inline_soql_query]];

In the forms above, [LValue] stands for any expression that can be placed on the left side of an assignment operator. These
include:

63

Language Constructs

Assignment Statements

A simple variable. For example:


Integer i = 1;
Account a = new Account();
Account[] accts = [SELECT Id FROM Account];

A de-referenced list element. For example:


ints[0] = 1;
accts[0].Name = 'Acme';

An sObject field reference that the context user has permission to edit. For example:
Account a = new Account(Name = 'Acme', BillingCity = 'San Francisco');
// IDs cannot be set manually
// a.Id = '00300000003T2PGAA0';

This code is invalid!

// Instead, insert the record. The system automatically assigns it an ID.


insert a;
// Fields also must be writeable for the context user
// a.CreatedDate = System.today(); This code is invalid because
//
createdDate is read-only!
// Since the account a has been inserted, it is now possible to
// create a new contact that is related to it
Contact c = new Contact(LastName = 'Roth', Account = a);
// Notice that you can write to the account name directly through the contact
c.Account.Name = 'salesforce.com';

Assignment is always done by reference. For example:


Account a = new Account();
Account b;
Account[] c = new Account[]{};
a.Name = 'Acme';
b = a;
c.add(a);
// These asserts should now be true. You can reference the data
// originally allocated to account a through account b and account list c.
System.assertEquals(b.Name, 'Acme');
System.assertEquals(c[0].Name, 'Acme');

Similarly, two lists can point at the same value in memory. For example:
Account[] a = new Account[]{new Account()};
Account[] b = a;
a[0].Name = 'Acme';
System.assert(b[0].Name == 'Acme');

In addition to =, other valid assignment operators include +=, *=, /=, |=, &=, ++, and --. See Understanding Expression
Operators on page 56.

64

Language Constructs

Conditional (If-Else) Statements

Conditional (If-Else) Statements


The conditional statement in Apex works similarly to Java:
if ([Boolean_condition])
// Statement 1
else
// Statement 2

The else portion is always optional, and always groups with the closest if. For example:
Integer x, sign;
// Your code
if (x <= 0) if (x == 0) sign = 0; else sign = -1;

is equivalent to:
Integer x, sign;
// Your code
if (x <= 0) {
if (x == 0) {
sign = 0;
} else {
sign = -1;
}
}

Repeated else if statements are also allowed. For example:


if (place == 1) {
medal_color = 'gold';
} else if (place == 2) {
medal_color = 'silver';
} else if (place == 3) {
medal_color = 'bronze';
} else {
medal_color = null;
}

Loops
Apex supports the following five types of procedural loops:

do {statement} while (Boolean_condition);


while (Boolean_condition) statement;
for (initialization; Boolean_exit_condition; increment) statement;
for (variable : array_or_set) statement;
for (variable : [inline_soql_query]) statement;

All loops allow for loop control structures:

break; exits the entire loop

65

Language Constructs

Do-While Loops

continue; skips to the next iteration of the loop

Do-While Loops
The Apex do-while loop repeatedly executes a block of code as long as a particular Boolean condition remains true. Its syntax
is:
do {
code_block
} while (condition);

Note: Curly braces ({}) are always required around a code_block.

As in Java, the Apex do-while loop does not check the Boolean condition statement until after the first loop is executed.
Consequently, the code block always runs at least once.
As an example, the following code outputs the numbers 1 - 10 into the debug log:
Integer count = 1;
do {
System.debug(count);
count++;
} while (count < 11);

While Loops
The Apex while loop repeatedly executes a block of code as long as a particular Boolean condition remains true. Its syntax
is:
while (condition) {
code_block
}

Note: Curly braces ({}) are required around a code_block only if the block contains more than one statement.

Unlike do-while, the while loop checks the Boolean condition statement before the first loop is executed. Consequently,
it is possible for the code block to never execute.
As an example, the following code outputs the numbers 1 - 10 into the debug log:
Integer count = 1;
while (count < 11) {
System.debug(count);
count++;
}

66

Language Constructs

For Loops

For Loops
Apex supports three variations of the for loop:

The traditional for loop:


for (init_stmt; exit_condition; increment_stmt) {
code_block
}

The list or set iteration for loop:


for (variable : list_or_set) {
code_block
}

where variable must be of the same primitive or sObject type as list_or_set.

The SOQL for loop:


for (variable : [soql_query]) {
code_block
}

or
for (variable_list : [soql_query]) {
code_block
}

Both variable and variable_list must be of the same sObject type as is returned by the soql_query.
Note: Curly braces ({}) are required around a code_block only if the block contains more than one statement.

Each is discussed further in the sections that follow.


Traditional For Loops
The traditional for loop in Apex corresponds to the traditional syntax used in Java and other languages. Its syntax is:
for (init_stmt; exit_condition; increment_stmt) {
code_block
}

When executing this type of for loop, the Apex runtime engine performs the following steps, in order:
1. Execute the init_stmt component of the loop. Note that multiple variables can be declared and/or initialized in this
statement.
2. Perform the exit_condition check. If true, the loop continues. If false, the loop exits.
3. Execute the code_block.
4. Execute the increment_stmt statement.
5. Return to Step 2.

67

Language Constructs

For Loops

As an example, the following code outputs the numbers 1 - 10 into the debug log. Note that an additional initialization variable,
j, is included to demonstrate the syntax:
for (Integer i = 0, j = 0; i < 10; i++) {
System.debug(i+1);
}

List or Set Iteration For Loops


The list or set iteration for loop iterates over all the elements in a list or set. Its syntax is:
for (variable : list_or_set) {
code_block
}

where variable must be of the same primitive or sObject type as list_or_set.


When executing this type of for loop, the Apex runtime engine assigns variable to each element in list_or_set, and
runs the code_block for each value.
For example, the following code outputs the numbers 1 - 10 to the debug log:
Integer[] myInts = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (Integer i : myInts) {
System.debug(i);
}

SOQL For Loops


SOQL for loops iterate over all of the sObject records returned by a SOQL query. The syntax of a SOQL for loop is either:
for (variable : [soql_query]) {
code_block
}

or
for (variable_list : [soql_query]) {
code_block
}

Both variable and variable_list must be of the same type as the sObjects that are returned by the soql_query.
As in standard SOQL queries, the [soql_query] statement can refer to code expressions in their WHERE clauses using the
: syntax. For example:
String s = 'Acme';
for (Account a : [SELECT Id, Name from Account
where Name LIKE :(s+'%')]) {
// Your code
}

68

Language Constructs

For Loops

The following example combines creating a list from a SOQL query, with the DML update method.
// Create a list of account records from a SOQL query
List<Account> accs = [SELECT Id, Name FROM Account WHERE Name = 'Siebel'];
// Loop through the list and update the Name field
for(Account a : accs){
a.Name = 'Oracle';
}
// Update the database
update accs;

SOQL For Loops Versus Standard SOQL Queries


SOQL for loops differ from standard SOQL statements because of the method they use to retrieve sObjects. While the
standard queries discussed in SOQL and SOSL Queries can retrieve either the count of a query or a number of object records,
SOQL for loops retrieve all sObjects, using efficient chunking with calls to the query and queryMore methods of the
SOAP API. Developers should always use a SOQL for loop to process query results that return many records, to avoid the
limit on heap size.
Note that queries including an aggregate function don't support queryMore. A runtime exception occurs if you use a query
containing an aggregate function that returns more than 2000 rows in a for loop.
SOQL For Loop Formats
SOQL for loops can process records one at a time using a single sObject variable, or in batches of 200 sObjects at a time
using an sObject list:

The single sObject format executes the for loop's <code_block> once per sObject record. Consequently, it is easy to
understand and use, but is grossly inefficient if you want to use data manipulation language (DML) statements within the
for loop body. Each DML statement ends up processing only one sObject at a time.
The sObject list format executes the for loop's <code_block> once per list of 200 sObjects. Consequently, it is a little
more difficult to understand and use, but is the optimal choice if you need to use DML statements within the for loop
body. Each DML statement can bulk process a list of sObjects at a time.

For example, the following code illustrates the difference between the two types of SOQL query for loops:
// Create a savepoint because the data should not be committed to the database
Savepoint sp = Database.setSavepoint();
insert new Account[]{new Account(Name = 'yyy'),
new Account(Name = 'yyy'),
new Account(Name = 'yyy')};
// The single sObject format executes the for loop once per returned record
Integer i = 0;
for (Account tmp : [SELECT Id FROM Account WHERE Name = 'yyy']) {
i++;
}
System.assert(i == 3); // Since there were three accounts named 'yyy' in the
// database, the loop executed three times
// The sObject list format executes the for loop once per returned batch
// of records
i = 0;
Integer j;
for (Account[] tmp : [SELECT Id FROM Account WHERE Name = 'yyy']) {
j = tmp.size();
i++;

69

Language Constructs

}
System.assert(j == 3); //
//
System.assert(i == 1); //
//
//

SOQL and SOSL Queries

The list should have contained the three accounts


named 'yyy'
Since a single batch can hold up to 100 records and,
only three records should have been returned, the
loop should have executed only once

// Revert the database to the original state


Database.rollback(sp);

Note:

The break and continue keywords can be used in both types of inline query for loop formats. When using the
sObject list format, continue skips to the next list of sObjects.
DML statements can only process up to 10,000 records at a time, and sObject list for loops process records in
batches of 200. Consequently, if you are inserting, updating, or deleting more than one record per returned record
in an sObject list for loop, it is possible to encounter runtime limit errors. See Understanding Execution Governors
and Limits on page 222.

SOQL and SOSL Queries


You can evaluate Salesforce Object Query Language (SOQL) or Salesforce Object Search Language (SOSL) statements
on-the-fly in Apex by surrounding the statement in square brackets.

SOQL Statements
SOQL statements evaluate to a list of sObjects, a single sObject, or an Integer for count method queries.
For example, you could retrieve a list of accounts that are named Acme:
List<Account> aa = [SELECT Id, Name FROM Account WHERE Name = 'Acme'];

From this list, you can access individual elements:


if (!aa.isEmpty()) {
// Execute commands
}

You can also create new objects from SOQL queries on existing ones. The following example creates a new contact for the
first account with the number of employees greater than 10:
Contact c = new Contact(Account = [SELECT Name FROM Account
WHERE NumberOfEmployees > 10 LIMIT 1]);
c.FirstName = 'James';
c.LastName = 'Yoyce';

Note that the newly created object contains null values for its fields, which will need to be set.
The count method can be used to return the number of rows returned by a query. The following example returns the total
number of contacts with the last name of Weissman:
Integer i = [SELECT COUNT() FROM Contact WHERE LastName = 'Weissman'];

70

Language Constructs

Working with SOQL and SOSL Query Results

You can also operate on the results using standard arithmetic:


Integer j = 5 * [SELECT COUNT() FROM Account];

For a full description of SOQL query syntax, see the Salesforce SOQL and SOSL Reference Guide.

SOSL Statements
SOSL statements evaluate to a list of lists of sObjects, where each list contains the search results for a particular sObject type.
The result lists are always returned in the same order as they were specified in the SOSL query. SOSL queries are only supported
in Apex classes and anonymous blocks. You cannot use a SOSL query in a trigger. If a SOSL query does not return any records
for a specified sObject type, the search results include an empty list for that sObject.
For example, you can return a list of accounts, contacts, opportunities, and leads that begin with the phrase map:
List<List<SObject>> searchList = [FIND 'map*' IN ALL FIELDS RETURNING Account (Id, Name),
Contact, Opportunity, Lead];

Note:
The syntax of the FIND clause in Apex differs from the syntax of the FIND clause in the SOAP API:

In Apex, the value of the FIND clause is demarcated with single quotes. For example:
FIND 'map*' IN ALL FIELDS RETURNING Account (Id, Name), Contact, Opportunity,
Lead

In the Force.com API, the value of the FIND clause is demarcated with braces. For example:
FIND {map*} IN ALL FIELDS RETURNING Account (Id, Name), Contact, Opportunity,
Lead

From searchList, you can create arrays for each object returned:
Account [] accounts = ((List<Account>)searchList[0]);
Contact [] contacts = ((List<Contact>)searchList[1]);
Opportunity [] opportunities = ((List<Opportunity>)searchList[2]);
Lead [] leads = ((List<Lead>)searchList[3]);

For a full description of SOSL query syntax, see the Salesforce SOQL and SOSL Reference Guide.

Working with SOQL and SOSL Query Results


SOQL and SOSL queries only return data for sObject fields that are selected in the original query. If you try to access a field
that was not selected in the SOQL or SOSL query (other than ID), you receive a runtime error, even if the field contains a
value in the database. The following code example causes a runtime error:
insert new Account(Name = 'Singha');
Account acc = [SELECT Id FROM Account WHERE Name = 'Singha' LIMIT 1];
// Note that name is not selected
String name = [SELECT Id FROM Account WHERE Name = 'Singha' LIMIT 1].Name;

71

Language Constructs

Working with SOQL Aggregate Functions

The following is the same code example rewritten so it does not produce a runtime error. Note that Name has been added as
part of the select statement, after Id.
insert new Account(Name = 'Singha');
Account acc = [SELECT Id FROM Account WHERE Name = 'Singha' LIMIT 1];
// Note that name is now selected
String name = [SELECT Id, Name FROM Account WHERE Name = 'Singha' LIMIT 1].Name;

Even if only one sObject field is selected, a SOQL or SOSL query always returns data as complete records. Consequently,
you must dereference the field in order to access it. For example, this code retrieves an sObject list from the database with a
SOQL query, accesses the first account record in the list, and then dereferences the record's AnnualRevenue field:
Double rev = [SELECT AnnualRevenue FROM Account
WHERE Name = 'Acme'][0].AnnualRevenue;
// When only one result is returned in a SOQL query, it is not necessary
// to include the list's index.
Double rev2 = [SELECT AnnualRevenue FROM Account
WHERE Name = 'Acme' LIMIT 1].AnnualRevenue;

The only situation in which it is not necessary to dereference an sObject field in the result of an SOQL query, is when the
query returns an Integer as the result of a COUNT operation:
Integer i = [SELECT COUNT() FROM Account];

Fields in records returned by SOSL queries must always be dereferenced.


Also note that sObject fields that contain formulas return the value of the field at the time the SOQL or SOSL query was
issued. Any changes to other fields that are used within the formula are not reflected in the formula field value until the record
has been saved and re-queried in Apex. Like other read-only sObject fields, the values of the formula fields themselves cannot
be changed in Apex.

Working with SOQL Aggregate Functions


Aggregate functions in SOQL, such as SUM() and MAX(), allow you to roll up and summarize your data in a query. For more
information on aggregate functions, see Aggregate Functions in the Salesforce SOQL and SOSL Reference Guide.
You can use aggregate functions without using a GROUP BY clause. For example, you could use the AVG() aggregate function
to find the average Amount for all your opportunities.
AggregateResult[] groupedResults
= [SELECT AVG(Amount)aver FROM Opportunity];
Object avgAmount = groupedResults[0].get('aver');

Note that any query that includes an aggregate function returns its results in an array of AggregateResult objects. AggregateResult
is a read-only sObject and is only used for query results.
Aggregate functions become a more powerful tool to generate reports when you use them with a GROUP BY clause. For
example, you could find the average Amount for all your opportunities by campaign.
AggregateResult[] groupedResults
= [SELECT CampaignId, AVG(Amount)
FROM Opportunity
GROUP BY CampaignId];
for (AggregateResult ar : groupedResults)

72

Language Constructs

Working with Very Large SOQL Queries

System.debug('Campaign ID' + ar.get('CampaignId'));


System.debug('Average amount' + ar.get('expr0'));
}

Any aggregated field in a SELECT list that does not have an alias automatically gets an implied alias with a format expri,
where i denotes the order of the aggregated fields with no explicit aliases. The value of i starts at 0 and increments for every
aggregated field with no explicit alias. For more information, see Using Aliases with GROUP BY in the Salesforce SOQL and
SOSL Reference Guide.
Note: Queries that include aggregate functions are subject to the same governor limits as other SOQL queries for
the total number of records returned. This limit includes any records included in the aggregation, not just the number
of rows returned by the query. If you encounter this limit, you should add a condition to the WHERE clause to reduce
the amount of records processed by the query.

Working with Very Large SOQL Queries


Your SOQL query may return so many sObjects that the limit on heap size is exceeded and an error occurs. To resolve, use
a SOQL query for loop instead, since it can process multiple batches of records through the use of internal calls to query
and queryMore.
For example, if the results are too large, the syntax below causes a runtime exception:
Account[] accts = [SELECT Id FROM Account];

Instead, use a SOQL query for loop as in one of the following examples:
// Use this format if you are not executing DML statements
// within the for loop
for (Account a : [SELECT Id, Name FROM Account
WHERE Name LIKE 'Acme%']) {
// Your code without DML statements here
}
// Use this format for efficiency if you are executing DML statements
// within the for loop
for (List<Account> accts : [SELECT Id, Name FROM Account
WHERE Name LIKE 'Acme%']) {
// Your code here
update accts;
}

The following example demonstrates a SOQL query for loop used to mass update records. Suppose you want to change the
last name of a contact across all records for contacts whose first and last names match a specified criteria:
public void massUpdate() {
for (List<Contact> contacts:
[SELECT FirstName, LastName FROM Contact]) {
for(Contact c : contacts) {
if (c.FirstName == 'Barbara' &&
c.LastName == 'Gordon') {
c.LastName = 'Wayne';
}
}
update contacts;
}
}

73

Language Constructs

Working with Very Large SOQL Queries

Instead of using a SOQL query in a for loop, the preferred method of mass updating records is to use batch Apex, which
minimizes the risk of hitting governor limits.
For more information, see SOQL For Loops on page 68.

More Efficient SOQL Queries


For best performance, SOQL queries must be selective, particularly for queries inside of triggers. To avoid long execution
times, non-selective SOQL queries may be terminated by the system. Developers will receive an error message when a
non-selective query in a trigger executes against an object that contains more than 100,000 records. To avoid this error, ensure
that the query is selective.
Selective SOQL Query Criteria

A query is selective when one of the query filters is on an indexed field and the query filter reduces the resulting
number of rows below a system-defined threshold. The performance of the SOQL query improves when two or
more filters used in the WHERE clause meet the mentioned conditions.
The selectivity threshold is 10% of the records for the first million records and less than 5% of the records after the
first million records, up to a maximum of 333,000 records. In some circumstances, for example with a query filter
that is an indexed standard field, the threshold may be higher. Also, the selectivity threshold is subject to change.

Custom Index Considerations for Selective SOQL Queries

The following fields are indexed by default: primary keys (Id, Name and Owner fields), foreign keys (lookup or
master-detail relationship fields), audit dates (such as LastModifiedDate), and custom fields marked as External ID
or Unique.
Salesforce.com Support can add custom indexes on request for customers.
A custom index can't be created on these types of fields: formula fields, multi-select picklists, currency fields in a
multicurrency organization, long text fields, and binary fields (fields of type blob, file, or encrypted text.) Note that
new data types, typically complex ones, may be added to Salesforce and fields of these types may not allow custom
indexing.
Typically, a custom index won't be used in these cases:
The value(s) queried for exceeds the system-defined threshold mentioned above
The filter operator is a negative operator such as NOT EQUAL TO (or !=), NOT CONTAINS, and NOT STARTS
WITH
The CONTAINS operator is used in the filter and the number of rows to be scanned exceeds 333,000. This is
because the CONTAINS operator requires a full scan of the index. Note that this threshold is subject to change.
When comparing with an empty value (Name != '')

However, there are other complex scenarios in which custom indexes won't be used. Contact your salesforce.com
representative if your scenario isn't covered by these cases or if you need further assistance with non-selective queries.
Examples of Selective SOQL Queries
To better understand whether a query on a large object is selective or not, let's analyze some queries. For these queries,
we will assume there are more than 100,000 records (including soft-deleted records, that is, deleted records that are still
in the Recycle Bin) for the Account sObject.
Query 1:
SELECT Id FROM Account WHERE Id IN (<list of account IDs>)

74

Language Constructs

Using SOQL Queries That Return One Record

The WHERE clause is on an indexed field (Id). If SELECT COUNT() FROM Account WHERE Id IN (<list of
account IDs>) returns fewer records than the selectivity threshold, the index on Id is used. This will typically be the
case since the list of IDs only contains a small amount of records.
Query 2:
SELECT Id FROM Account WHERE Name != ''

Since Account is a large object even though Name is indexed (primary key), this filter returns most of the records, making
the query non-selective.
Query 3:
SELECT Id FROM Account WHERE Name != '' AND CustomField__c = 'ValueA'

Here we have to see if each filter, when considered individually, is selective. As we saw in the previous example the first
filter isn't selective. So let's focus on the second one. If the count of records returned by SELECT COUNT() FROM
Account WHERE CustomField__c = 'ValueA' is lower than the selectivity threshold, and CustomField__c is
indexed, the query is selective.
Query 4:
SELECT Id FROM Account WHERE FormulaField__c = 'ValueA'

Since a formula field can't be custom indexed, the query won't be selective, regardless of how many records have actually
'ValueA'. Remember that filtering on a formula field should be avoided, especially when querying on large objects, since
the formula needs to be evaluated for every Account record on the fly.

Using SOQL Queries That Return One Record


SOQL queries can be used to assign a single sObject value when the result list contains only one element. When the L-value
of an expression is a single sObject type, Apex automatically assigns the single sObject record in the query result list to the
L-value. A runtime exception results if zero sObjects or more than one sObject is found in the list. For example:
List<Account> accts = [SELECT Id FROM Account];
// These lines of code are only valid if one row is returned from
// the query. Notice that the second line dereferences the field from the
// query without assigning it to an intermediary sObject variable.
Account acct = [SELECT Id FROM Account];
String name = [SELECT Name FROM Account].Name;

Improving Performance by Not Searching on Null Values


In your SOQL and SOSL queries, avoid searching records that contain null values. Filter out null values first to improve
performance. In the following example, any records where the treadID value is null are filtered out of the returned values.
Public class TagWS {
/* getThreadTags
*
* a quick method to pull tags not in the existing list
*

75

Language Constructs

Understanding Foreign Key and Parent-Child Relationship SOQL Queries

*/
public static webservice List<String>
getThreadTags(String threadId, List<String> tags) {
system.debug(LoggingLevel.Debug,tags);
List<String> retVals = new List<String>();
Set<String> tagSet = new Set<String>();
Set<String> origTagSet = new Set<String>();
origTagSet.addAll(tags);
// Note WHERE clause verifies that threadId is not null
for(CSO_CaseThread_Tag__c t :
[SELECT Name FROM CSO_CaseThread_Tag__c
WHERE Thread__c = :threadId AND
WHERE threadID != null])
{
tagSet.add(t.Name);
}
for(String x : origTagSet) {
// return a minus version of it so the UI knows to clear it
if(!tagSet.contains(x)) retVals.add('-' + x);
}
for(String x : tagSet) {
// return a plus version so the UI knows it's new
if(!origTagSet.contains(x)) retvals.add('+' + x);
}
return retVals;
}

Understanding Foreign Key and Parent-Child Relationship SOQL Queries


The SELECT statement of a SOQL query can be any valid SOQL statement, including foreign key and parent-child record
joins. If foreign key joins are included, the resulting sObjects can be referenced using normal field notation. For example:
System.debug([SELECT Account.Name FROM Contact
WHERE FirstName = 'Caroline'].Account.Name);

Additionally, parent-child relationships in sObjects act as SOQL queries as well. For example:
for (Account a : [SELECT Id, Name, (SELECT LastName FROM Contacts)
FROM Account
WHERE Name = 'Acme']) {
Contact[] cons = a.Contacts;
}
//The following example also works because we limit to only 1 contact
for (Account a : [SELECT Id, Name, (SELECT LastName FROM Contacts LIMIT 1)
FROM Account
WHERE Name = 'testAgg']) {
Contact c = a.Contacts;
}

76

Language Constructs

Using Apex Variables in SOQL and SOSL Queries

Using Apex Variables in SOQL and SOSL Queries


SOQL and SOSL statements in Apex can reference Apex code variables and expressions if they are preceded by a colon (:).
This use of a local code variable within a SOQL or SOSL statement is called a bind. The Apex parser first evaluates the local
variable in code context before executing the SOQL or SOSL statement. Bind expressions can be used as:

The search string in FIND clauses.


The filter literals in WHERE clauses.
The value of the IN or NOT IN operator in WHERE clauses, allowing filtering on a dynamic set of values. Note that this is
of particular use with a list of IDs or Strings, though it works with lists of any type.
The division names in WITH DIVISION clauses.
The numeric value in LIMIT clauses.

Bind expressions can't be used with other clauses, such as INCLUDES.


For example:
Account A = new Account(Name='xxx');
insert A;
Account B;
// A simple bind
B = [SELECT Id FROM Account WHERE Id = :A.Id];
// A bind with arithmetic
B = [SELECT Id FROM Account
WHERE Name = :('x' + 'xx')];
String s = 'XXX';
// A bind with expressions
B = [SELECT Id FROM Account
WHERE Name = :'XXXX'.substring(0,3)];
// A bind with an expression that is itself a query result
B = [SELECT Id FROM Account
WHERE Name = :[SELECT Name FROM Account
WHERE Id = :A.Id].Name];
Contact C = new Contact(LastName='xxx', AccountId=A.Id);
insert new Contact[]{C, new Contact(LastName='yyy',
accountId=A.id)};
// Binds in both the parent and aggregate queries
B = [SELECT Id, (SELECT Id FROM Contacts
WHERE Id = :C.Id)
FROM Account
WHERE Id = :A.Id];
// One contact returned
Contact D = B.Contacts;
// A limit bind
Integer i = 1;
B = [SELECT Id FROM Account LIMIT :i];
// An IN-bind with an Id list. Note that a list of sObjects
// can also be used--the Ids of the objects are used for
// the bind
Contact[] cc = [SELECT Id FROM Contact LIMIT 2];
Task[] tt = [SELECT Id FROM Task WHERE WhoId IN :cc];

77

Language Constructs

Querying All Records with a SOQL Statement

// An IN-bind with a String list


String[] ss = new String[]{'a', 'b'};
Account[] aa = [SELECT Id FROM Account
WHERE AccountNumber IN :ss];
// A SOSL query with binds in all possible clauses
String myString1
String myString2
Integer myInt3 =
String myString4
Integer myInt5 =

= 'aaa';
= 'bbb';
11;
= 'ccc';
22;

List<List<SObject>> searchList = [FIND :myString1 IN ALL FIELDS


RETURNING
Account (Id, Name WHERE Name LIKE :myString2
LIMIT :myInt3),
Contact,
Opportunity,
Lead
WITH DIVISION =:myString4
LIMIT :myInt5];

Querying All Records with a SOQL Statement


SOQL statements can use the ALL ROWS keywords to query all records in an organization, including deleted records and
archived activities. For example:
System.assertEquals(2, [SELECT COUNT() FROM Contact WHERE AccountId = a.Id ALL ROWS]);

You can use ALL ROWS to query records in your organization's Recycle Bin. You cannot use the ALL ROWS keywords with
the FOR UPDATE keywords.

Locking Statements
Apex allows developers to lock sObject records while they are being updated in order to prevent race conditions and other
thread safety problems. While an sObject record is locked, no other program or user is allowed to make updates.
To lock a set of sObject records in Apex, embed the keywords FOR UPDATE after any inline SOQL statement. For example,
the following statement, in addition to querying for two accounts, also locks the accounts that are returned:
Account [] accts = [SELECT Id FROM Account LIMIT 2 FOR UPDATE];

Note: You cannot use the ORDER BY keywords in any SOQL query that uses locking. However, query results are
automatically ordered by ID.
While the accounts are locked by this call, data manipulation language (DML) statements can modify their field values in the
database in the transaction.
Caution: Use care when setting locks in your Apex code. See Avoiding Deadlocks, below.

78

Language Constructs

Locking in a SOQL For Loop

Locking in a SOQL For Loop


The FOR UPDATE keywords can also be used within SOQL for loops. For example:
for (Account[] accts : [SELECT Id FROM Account
FOR UPDATE]) {
// Your code
}

As discussed in SOQL For Loops, the example above corresponds internally to calls to the query() and queryMore()
methods in the SOAP API.
Note that there is no commit statement. If your Apex trigger completes successfully, any database changes are automatically
committed. If your Apex trigger does not complete successfully, any changes made to the database are rolled back.

Avoiding Deadlocks
Note that Apex has the possibility of deadlocks, as does any other procedural logic language involving updates to multiple
database tables or rows. To avoid such deadlocks, the Apex runtime engine:
1. First locks sObject parent records, then children.
2. Locks sObject records in order of ID when multiple records of the same type are being edited.
As a developer, use care when locking rows to ensure that you are not introducing deadlocks. Verify that you are using standard
deadlock avoidance techniques by accessing tables and rows in the same order from all locations in an application.

Transaction Control
All requests are delimited by the trigger, class method, Web Service, Visualforce page or anonymous block that executes the
Apex code. If the entire request completes successfully, all changes are committed to the database. For example, suppose a
Visualforce page called an Apex controller, which in turn called an additional Apex class. Only when all the Apex code has
finished running and the Visualforce page has finished running, are the changes committed to the database. If the request
does not complete successfully, all database changes are rolled back.
However, sometimes during the processing of records, your business rules require that partial work (already executed DML
statements) be rolled back so that the processing can continue in another direction. Apex gives you the ability to generate a
savepoint, that is, a point in the request that specifies the state of the database at that time. Any DML statement that occurs
after the savepoint can be discarded, and the database can be restored to the same condition it was in at the time you generated
the savepoint.
The following limitations apply to generating savepoint variables and rolling back the database:

If you set more than one savepoint, then roll back to a savepoint that is not the last savepoint you generated, the later
savepoint variables become invalid. For example, if you generated savepoint SP1 first, savepoint SP2 after that, and then
you rolled back to SP1, the variable SP2 would no longer be valid. You will receive a runtime error if you try to use it.
References to savepoints cannot cross trigger invocations, because each trigger invocation is a new execution context. If
you declare a savepoint as a static variable then try to use it across trigger contexts you will receive a runtime error.
Each savepoint you set counts against the governor limit for DML statements.

79

Language Constructs

Exception Statements

Each rollback counts against the governor limit for DML statements. You will receive a runtime error if you try to rollback
the database additional times.

The following is an example using the setSavepoint and rollback Database methods.
Account a = new Account(Name = 'xxx'); insert a;
System.assertEquals(null, [SELECT AccountNumber FROM Account WHERE Id = :a.Id].
AccountNumber);
// Create a savepoint while AccountNumber is null
Savepoint sp = Database.setSavepoint();
// Change the account number
a.AccountNumber = '123';
update a;
System.assertEquals('123', [SELECT AccountNumber FROM Account WHERE Id = :a.Id].
AccountNumber);
// Rollback to the previous null value
Database.rollback(sp);
System.assertEquals(null, [SELECT AccountNumber FROM Account WHERE Id = :a.Id].
AccountNumber);

Exception Statements
Apex uses exceptions to note errors and other events that disrupt the normal flow of code execution. throw statements can be
used to generate exceptions, while try, catch, and finally can be used to gracefully recover from an exception.
You can also create your own exceptions using the Exception class. For more information, see Exception Class on page 442.

Throw Statements
A throw statement allows you to signal that an error has occurred. To throw an exception, use the throw statement and
provide it with an exception object to provide information about the specific error. For example:
throw exceptionObject;

Try-Catch-Finally Statements
The try, catch, and finally statements can be used to gracefully recover from a thrown exception:

The try statement identifies a block of code in which an exception can occur.
The catch statement identifies a block of code that can handle a particular type of exception. A single try statement can
have multiple associated catch statements, however, each catch statement must have a unique exception type.
The finally statement optionally identifies a block of code that is guaranteed to execute and allows you to clean up after
the code enclosed in the try block. A single try statement can have only one associated finally statement.

80

Language Constructs

Try-Catch-Finally Statements

Syntax
The syntax of these statements is as follows:
try {
code_block
} catch (exceptionType) {
code_block
}
// Optional catch statements for other exception types.
// Note that the general exception type, 'Exception',
// must be the last catch block when it is used.
} catch (Exception e) {
code_block
}
// Optional finally statement
} finally {
code_block
}

Example
For example:
try {
// Your code here
} catch (ListException e) {
// List Exception handling code here
} catch (Exception e) {
// Generic exception handling code here
}

Note: Limit exceptions caused by an execution governor cannot be caught. See Understanding Execution Governors
and Limits on page 222.

81

Chapter 3
Invoking Apex
In this chapter ...

Triggers
Apex Scheduler
Anonymous Blocks
Apex in AJAX

You can invoke your Apex code using one of several mechanisms. You can write
an Apex trigger and have your trigger code invoked for the events your trigger
specifiesbefore or after a certain operation for a specified sObject type. You
can also write an Apex class and schedule it to run at specified intervals, or run
code snippets in an anonymous block. Finally, you can use the Ajax toolkit to
invoke Web service methods implemented in Apex.
This chapter includes the following:

Triggers
Apex scheduler (for Apex classes only)
Anonymous Blocks
AJAX Toolkit

82

Invoking Apex

Triggers

Triggers
Apex can be invoked through the use of triggers. A trigger is Apex code that executes before or after the following types of
operations:

insert
update
delete
merge
upsert
undelete

For example, you can have a trigger run before an object's records are inserted into the database, after records have been deleted,
or even after a record is restored from the Recycle Bin.
You can define triggers for any top-level standard object, such as a Contact or an Account, but not for standard child objects,
such as a ContactRole.

For case comments, click Your Name > Setup > Customize > Cases > Case Comments > Triggers.
For email messages, click Your Name > Setup > Customize > Cases > Email Messages > Triggers.

Triggers can be divided into two types:

Before triggers can be used to update or validate record values before they are saved to the database.
After triggers can be used to access field values that are set by the database (such as a record's Id or lastUpdated field),
and to affect changes in other records, such as logging into an audit table or firing asynchronous events with a queue.

Triggers can also modify other records of the same type as the records that initially fired the trigger. For example, if a trigger
fires after an update of contact A, the trigger can also modify contacts B, C, and D. Because triggers can cause other records to
change, and because these changes can, in turn, fire more triggers, the Apex runtime engine considers all such operations a
single unit of work and sets limits on the number of operations that can be performed to prevent infinite recursion. See
Understanding Execution Governors and Limits on page 222.
Additionally, if you update or delete a record in its before trigger, or delete a record in its after trigger, you will receive a runtime
error. This includes both direct and indirect operations. For example, if you update account A, and the before update trigger
of account A inserts contact B, and the after insert trigger of contact B queries for account A and updates it using the DML
update statement or database method, then you are indirectly updating account A in its before trigger, and you will receive
a runtime error.

Implementation Considerations
Before creating triggers, consider the following:

upsert triggers fire both before and after insert or before and after update triggers as appropriate.
merge triggers fire both before and after delete triggers for the losing records and before update triggers for the

winning record only. See Triggers and Merge Statements on page 91.
Triggers that execute after a record has been undeleted only work with specific objects. See Triggers and Recovered Records
on page 92.
Field history is not recorded until the end of a trigger. If you query field history in a trigger, you will not see any history
for the current transaction.

83

Invoking Apex

Bulk Triggers

For Apex saved using Salesforce.com API version 20.0 or earlier, if an API call causes a trigger to fire, the batch of 200
records to process is further split into batches of 100 records. For Apex saved using Salesforce.com API version 21.0 and
later, no further splits of API batches occur. Note that static variable values are reset between batches, but governor limits
are not. Do not use static variables to track state information between batches.

Bulk Triggers
All triggers are bulk triggers by default, and can process multiple records at a time. You should always plan on processing more
than one record at a time.
Note: An Event object that is defined as recurring is not processed in bulk for insert, delete, or update triggers.

Bulk triggers can handle both single record updates and bulk operations like:

Data import
Force.com Bulk API calls
Mass actions, such as record owner changes and deletes
Recursive Apex methods and triggers that invoke bulk DML statements

Trigger Syntax
To define a trigger, use the following syntax:
trigger triggerName on ObjectName (trigger_events) {
code_block
}

where trigger_events can be a comma-separated list of one or more of the following events:

before insert
before update
before delete
after insert
after update
after delete
after undelete

Note:

You can only use the webService keyword in a trigger when it is in a method defined as asynchronous; that is,
when the method is defined with the @future keyword.
A trigger invoked by an insert, delete, or update of a recurring event or recurring task results in a runtime
error when the trigger is called in bulk from the Force.com API.

84

Invoking Apex

Trigger Context Variables

For example, the following code defines a trigger for the before insert and before update events on the Account
object:
trigger myAccountTrigger on Account (before insert, before update) {
// Your code here
}

The code block of a trigger cannot contain the static keyword. Triggers can only contain keywords applicable to an inner
class. In addition, you do not have to manually commit any database changes made by a trigger. If your Apex trigger completes
successfully, any database changes are automatically committed. If your Apex trigger does not complete successfully, any
changes made to the database are rolled back.

Trigger Context Variables


All triggers define implicit variables that allow developers to access runtime context. These variables are contained in the
System.Trigger class:
Variable

Usage

isExecuting

Returns true if the current context for the Apex code is a trigger, not a Visualforce page, a
Web service, or an executeanonymous() API call.

isInsert

Returns true if this trigger was fired due to an insert operation, from the Salesforce user
interface, Apex, or the API.

isUpdate

Returns true if this trigger was fired due to an update operation, from the Salesforce user
interface, Apex, or the API.

isDelete

Returns true if this trigger was fired due to a delete operation, from the Salesforce user
interface, Apex, or the API.

isBefore

Returns true if this trigger was fired before any record was saved.

isAfter

Returns true if this trigger was fired after all records were saved.

isUndelete

Returns true if this trigger was fired after a record is recovered from the Recycle Bin (that is,
after an undelete operation from the Salesforce user interface, Apex, or the API.)

new

Returns a list of the new versions of the sObject records.


Note that this sObject list is only available in insert and update triggers, and the records
can only be modified in before triggers.

newMap

A map of IDs to the new versions of the sObject records.


Note that this map is only available in before update, after insert, and after
update triggers.

old

Returns a list of the old versions of the sObject records.


Note that this sObject list is only available in update and delete triggers.

oldMap

A map of IDs to the old versions of the sObject records.


Note that this map is only available in update and delete triggers.

85

Invoking Apex

Trigger Context Variables

Variable

Usage

size

The total number of records in a trigger invocation, both old and new.

Note: If any record that fires a trigger includes an invalid field value (for example, a formula that divides by zero),
that value is set to null in the new, newMap, old, and oldMap trigger context variables.
For example, in this simple trigger, Trigger.new is a list of sObjects and can be iterated over in a for loop, or used as a
bind variable in the IN clause of a SOQL query:
Trigger t on Account (after insert) {
for (Account a : Trigger.new) {
// Iterate over each sObject
}
// This single query finds every contact that is associated with any of the
// triggering accounts. Note that although Trigger.new is a collection of
// records, when used as a bind variable in a SOQL query, Apex automatically
// transforms the list of records into a list of corresponding Ids.
Contact[] cons = [SELECT LastName FROM Contact
WHERE AccountId IN :Trigger.new];
}

This trigger uses Boolean context variables like Trigger.isBefore and Trigger.isDelete to define code that only
executes for specific trigger conditions:
trigger myAccountTrigger on Account(before delete, before insert, before update,
after delete, after insert, after update) {
if (Trigger.isBefore) {
if (Trigger.isDelete) {
// In a before delete trigger, the trigger accesses the records that will be
// deleted with the Trigger.old list.
for (Account a : Trigger.old) {
if (a.name != 'okToDelete') {
a.addError('You can\'t delete this record!');
}
}
} else {
// In before insert or before update triggers, the trigger accesses the new records
// with the Trigger.new list.
for (Account a : Trigger.new) {
if (a.name == 'bad') {
a.name.addError('Bad name');
}
}
if (Trigger.isInsert) {
for (Account a : Trigger.new) {
System.assertEquals('xxx', a.accountNumber);
System.assertEquals('industry', a.industry);
System.assertEquals(100, a.numberofemployees);
System.assertEquals(100.0, a.annualrevenue);
a.accountNumber = 'yyy';
}
// If the trigger is not a before trigger, it must be an after trigger.
} else {
if (Trigger.isInsert) {
List<Contact> contacts = new List<Contact>();

86

Invoking Apex

Context Variable Considerations

for (Account a : Trigger.new) {


if(a.Name == 'makeContact') {
contacts.add(new Contact (LastName = a.Name,
AccountId = a.Id));
}
}
insert contacts;
}
}
}}}

Context Variable Considerations


Be aware of the following considerations for trigger context variables:

trigger.new and trigger.old cannot be used in Apex DML operations.

You can use an object to change its own field values using trigger.new, but only in before triggers. In all after triggers,
trigger.new is not saved, so a runtime exception is thrown.
trigger.old is always read-only.
You cannot delete trigger.new.

The following table lists considerations about certain actions in different trigger events:
Trigger Event

Can change fields using


trigger.new

Can update original object


using an update DML
operation

Can delete original object


using a delete DML
operation

Not applicable. The original


object has not been created;
nothing can reference it, so
nothing can update it.

Not applicable. The original


object has not been created;
nothing can reference it, so
nothing can update it.

before insert

Allowed.

after insert

Not allowed. A runtime error Allowed.


is thrown, as trigger.new
is already saved.

before update

Allowed.

after update

Not allowed. A runtime error Allowed. Even though bad


is thrown, as trigger.new code could cause an infinite
is already saved.
recursion doing this
incorrectly, the error would be
found by the governor limits.

before delete

Not allowed. A runtime error


is thrown. trigger.new is
not available in before delete
triggers.

Allowed, but unnecessary. The


object is deleted immediately
after being inserted.

Not allowed. A runtime error Not allowed. A runtime error


is thrown.
is thrown.
Allowed. The updates are
saved before the object is
deleted, so if the object is
undeleted, the updates become
visible.

Allowed. The updates are


Not allowed. A runtime error
saved before the object is
is thrown. The deletion is
deleted, so if the object is
already in progress.
undeleted, the updates become
visible.

87

Invoking Apex

Trigger Event

Common Bulk Trigger Idioms

Can change fields using


trigger.new

Can update original object


using an update DML
operation

Can delete original object


using a delete DML
operation

after delete

Not allowed. A runtime error Not applicable. The object has Not applicable. The object has
is thrown. trigger.new is already been deleted.
already been deleted.
not available in after delete
triggers.

after undelete

Not allowed. A runtime error Allowed.


is thrown. trigger.old is
not available in after undelete
triggers.

Allowed, but unnecessary. The


object is deleted immediately
after being inserted.

Common Bulk Trigger Idioms


Although bulk triggers allow developers to process more records without exceeding execution governor limits, they can be
more difficult for developers to understand and code because they involve processing batches of several records at a time. The
following sections provide examples of idioms that should be used frequently when writing in bulk.
Using Maps and Sets in Bulk Triggers
Set and map data structures are critical for successful coding of bulk triggers. Sets can be used to isolate distinct records, while
maps can be used to hold query results organized by record ID.
For example, this bulk trigger from the sample quoting application first adds each pricebook entry associated with the
OpportunityLineItem records in Trigger.new to a set, ensuring that the set contains only distinct elements. It then queries
the PricebookEntries for their associated product color, and places the results in a map. Once the map is created, the trigger
iterates through the OpportunityLineItems in Trigger.new and uses the map to assign the appropriate color.
// When a new line item is added to an opportunity, this trigger copies the value of the
// associated product's color to the new record.
trigger oppLineTrigger on OpportunityLineItem (before insert) {
// For every OpportunityLineItem record, add its associated pricebook entry
// to a set so there are no duplicates.
Set<Id> pbeIds = new Set<Id>();
for (OpportunityLineItem oli : Trigger.new)
pbeIds.add(oli.pricebookentryid);
// Query the PricebookEntries for their associated product color and place the results
// in a map.
Map<Id, PricebookEntry> entries = new Map<Id, PricebookEntry>(
[select product2.color__c from pricebookentry
where id in :pbeIds]);
// Now use the map to set the appropriate color on every OpportunityLineItem processed
// by the trigger.
for (OpportunityLineItem oli : Trigger.new)
oli.color__c = entries.get(oli.pricebookEntryId).product2.color__c;
}

88

Invoking Apex

Defining Triggers

Correlating Records with Query Results in Bulk Triggers


Use the Trigger.newMap and Trigger.oldMap ID-to-sObject maps to correlate records with query results. For example,
this trigger from the sample quoting app uses Trigger.oldMap to create a set of unique IDs (Trigger.oldMap.keySet()).
The set is then used as part of a query to create a list of quotes associated with the opportunities being processed by the trigger.
For every quote returned by the query, the related opportunity is retrieved from Trigger.oldMap and prevented from being
deleted:
trigger oppTrigger on Opportunity (before delete) {
for (Quote__c q : [SELECT opportunity__c FROM quote__c
WHERE opportunity__c IN :Trigger.oldMap.keySet()]) {
Trigger.oldMap.get(q.opportunity__c).addError('Cannot delete
opportunity with a quote');
}
}

Using Triggers to Insert or Update Records with Unique Fields


When an insert or upsert event causes a record to duplicate the value of a unique field in another new record in that batch,
the error message for the duplicate record includes the ID of the first record. However, it is possible that the error message
may not be correct by the time the request is finished.
When there are triggers present, the retry logic in bulk operations causes a rollback/retry cycle to occur. That retry cycle assigns
new keys to the new records. For example, if two records are inserted with the same value for a unique field, and you also have
an insert event defined for a trigger, the second duplicate record fails, reporting the ID of the first record. However, once
the system rolls back the changes and re-inserts the first record by itself, the record receives a new ID. That means the error
message reported by the second record is no longer valid.

Defining Triggers
Trigger code is stored as metadata under the object with which they are associated. To define a trigger in Salesforce:
1. For a standard object, click Your Name > Setup > Customize, click the name of the object, then click Triggers.
For a custom object, click Your Name > Setup > Create > Objects and click the name of the object.
For campaign members, click Your Name > Setup > Customize > Campaigns > Campaign Member > Triggers.
For case comments, click Your Name > Setup > Customize > Cases > Case Comments > Triggers.
For email messages, click Your Name > Setup > Customize > Cases > Email Messages > Triggers.
For the Attachment, ContentDocument, and Note standard objects, you cant create a trigger in the Salesforce user interface.
For these objects, create a trigger using development tools, such as the Developer Console or the Force.com IDE.
Alternatively, you can also use the Metadata API.
2. In the Triggers related list, click New.
3. Click Version Settings to specify the version of Apex and the API used with this trigger. If your organization has installed
managed packages from the AppExchange, you can also specify which version of each managed package to use with this
trigger. Use the default values for all versions. This associates the trigger with the most recent version of Apex and the
API, as well as each managed package. You can specify an older version of a managed package if you want to access
components or functionality that differs from the most recent package version.
4. Select the Is Active checkbox if the trigger should be compiled and enabled. Leave this checkbox deselected if you only
want to store the code in your organization's metadata. This checkbox is selected by default.

89

Invoking Apex

Defining Triggers

5. In the Body text box, enter the Apex for the trigger. A single trigger can be up to 1 million characters in length.
To define a trigger, use the following syntax:
trigger triggerName on ObjectName (trigger_events) {
code_block
}

where trigger_events can be a comma-separated list of one or more of the following events:

before insert
before update
before delete
after insert
after update
after delete
after undelete

Note:

You can only use the webService keyword in a trigger when it is in a method defined as asynchronous; that
is, when the method is defined with the @future keyword.
A trigger invoked by an insert, delete, or update of a recurring event or recurring task results in a runtime
error when the trigger is called in bulk from the Force.com API.

6. Click Save.
Note: Triggers are stored with an isValid flag that is set to true as long as dependent metadata has not changed
since the trigger was last compiled. If any changes are made to object names or fields that are used in the trigger,
including superficial changes such as edits to an object or field description, the isValid flag is set to false until the
Apex compiler reprocesses the code. Recompiling occurs when the trigger is next executed, or when a user re-saves
the trigger in metadata.
If a lookup field references a record that has been deleted, Salesforce clears the value of the lookup field by default.
Alternatively, you can choose to prevent records from being deleted if theyre in a lookup relationship.

The Apex Trigger Editor


When editing Visualforce or Apex, either in the Visualforce development mode footer or from Setup, an editor is available
with the following functionality:
Syntax highlighting
The editor automatically applies syntax highlighting for keywords and all functions and operators.
Search ( )
Search enables you to search for text within the current page, class, or trigger. To use search, enter a string in the Search
textbox and click Find Next.

To replace a found search string with another string, enter the new string in the Replace textbox and click replace
to replace just that instance, or Replace All to replace that instance and all other instances of the search string that
occur in the page, class, or trigger.
To make the search operation case sensitive, select the Match Case option.

90

Invoking Apex

Triggers and Merge Statements

To use a regular expression as your search string, select the Regular Expressions option. The regular expressions
follow Javascript's regular expression rules. A search using regular expressions can find strings that wrap over more
than one line.
If you use the replace operation with a string found by a regular expression, the replace operation can also bind regular
expression group variables ($1, $2, and so on) from the found search string. For example, to replace an <H1> tag
with an <H2> tag and keep all the attributes on the original <H1> intact, search for <H1(\s+)(.*)> and replace it
with <H2$1$2>.

Go to line ( )
This button allows you to highlight a specified line number. If the line is not currently visible, the editor scrolls to that
line.
Undo ( ) and Redo ( )
Use undo to reverse an editing action and redo to recreate an editing action that was undone.
Font size
Select a font size from the drop-down list to control the size of the characters displayed in the editor.
Line and column position
The line and column position of the cursor is displayed in the status bar at the bottom of the editor. This can be used
with go to line (

) to quickly navigate through the editor.

Line and character count


The total number of lines and characters is displayed in the status bar at the bottom of the editor.

Triggers and Merge Statements


Merge events do not fire their own trigger events. Instead, they fire delete and update events as follows:
Deletion of losing records
A single merge operation fires a single delete event for all records that are deleted in the merge. To determine which
records were deleted as a result of a merge operation use the MasterRecordId field in Trigger.old. When a record
is deleted after losing a merge operation, its MasterRecordId field is set to the ID of the winning record. The
MasterRecordId field is only set in after delete trigger events. If your application requires special handling for
deleted records that occur as a result of a merge, you need to use the after delete trigger event.
Update of the winning record
A single merge operation fires a single update event for the winning record only. Any child records that are reparented
as a result of the merge operation do not fire triggers.
For example, if two contacts are merged, only the delete and update contact triggers fire. No triggers for records related to the
contacts, such as accounts or opportunities, fire.
The following is the order of events when a merge occurs:
1. The before delete trigger fires.
2. The system deletes the necessary records due to the merge, assigns new parent records to the child records, and sets the
MasterRecordId field on the deleted records.
3. The after delete trigger fires.

91

Invoking Apex

Triggers and Recovered Records

4. The system does the specific updates required for the master record. Normal update triggers apply.

Triggers and Recovered Records


The after undelete trigger event only works with recovered recordsthat is, records that were deleted and then recovered
from the Recycle Bin through the undelete DML statement. These are also called undeleted records.
The after undelete trigger events only run on top-level objects. For example, if you delete an Account, an Opportunity
may also be deleted. When you recover the Account from the Recycle Bin, the Opportunity is also recovered. If there is an
after undelete trigger event associated with both the Account and the Opportunity, only the Account after undelete
trigger event executes.
The after undelete trigger event only fires for the following objects:

Account
Asset
Campaign
Case
Contact
ContentDocument
Contract
Custom objects
Event
Lead
Opportunity
Product
Solution
Task

Triggers and Order of Execution


When you save a record with an insert, update, or upsert statement, Salesforce performs the following events in order.
Note: Before Salesforce executes these events on the server, the browser runs JavaScript validation if the record contains
any dependent picklist fields. The validation limits each dependent picklist field to its available values. No other
validation occurs on the client side.
On the server, Salesforce:
1. Loads the original record from the database or initializes the record for an upsert statement.
2. Loads the new record field values from the request and overwrites the old values.
If the request came from a standard UI edit page, Salesforce runs system validation to check the record for:

Compliance with layout-specific rules


Required values at the layout level and field-definition level
Valid field formats
Maximum field length

92

Invoking Apex

Triggers and Order of Execution

Salesforce doesn't perform system validation in this step when the request comes from other sources, such as an Apex
application or a SOAP API call.
3. Executes all before triggers.
4. Runs most system validation steps again, such as verifying that all required fields have a non-null value, and runs any
user-defined validation rules. The only system validation that Salesforce doesn't run a second time (when the request comes
from a standard UI edit page) is the enforcement of layout-specific rules.
5. Saves the record to the database, but doesn't commit yet.
6. Executes all after triggers.
7. Executes assignment rules.
8. Executes auto-response rules.
9. Executes workflow rules.
10. If there are workflow field updates, updates the record again.
11. If the record was updated with workflow field updates, fires before and after triggers one more time (and only one
more time), in addition to standard validations. Custom validation rules are not run again.
Note: The before and after triggers fire one more time only if something needs to be updated. If the fields
have already been set to a value, the triggers are not fired again.
12. Executes escalation rules.
13. If the record contains a roll-up summary field or is part of a cross-object workflow, performs calculations and updates the
roll-up summary field in the parent record. Parent record goes through save procedure.
14. If the parent record is updated, and a grand-parent record contains a roll-up summary field or is part of a cross-object
workflow, performs calculations and updates the roll-up summary field in the parent record. Grand-parent record goes
through save procedure.
15. Executes Criteria Based Sharing evaluation.
16. Commits all DML operations to the database.
17. Executes post-commit logic, such as sending email.
Note: During a recursive save, Salesforce skips steps 7 through 14.

Additional Considerations
Please note the following when working with triggers:

When Enable Validation and Triggers from Lead Convert is selected, if the lead conversion creates an
opportunity and the opportunity has Apex before triggers associated with it, the triggers run immediately after the opportunity
is created, before the opportunity contact role is created. For more information, see Customizing Lead Settings in the
Salesforce online help.
If you are using before triggers to set Stage and Forecast Category for an opportunity record, the behavior is as
follows:
If you set Stage and Forecast Category, the opportunity record contains those exact values.
If you set Stage but not Forecast Category, the Forecast Category value on the opportunity record defaults
to the one associated with trigger Stage.
If you reset Stage to a value specified in an API call or incoming from the user interface, the Forecast Category
value should also come from the API call or user interface. If no value for Forecast Category is specified and the
incoming Stage is different than the trigger Stage, the Forecast Category defaults to the one associated with
trigger Stage. If the trigger Stage and incoming Stage are the same, the Forecast Category is not defaulted.

93

Invoking Apex

Operations That Don't Invoke Triggers

If you are cloning an opportunity with products, the following events occur in order:
1. The parent opportunity is saved according to the list of events shown above.
2. The opportunity products are saved according to the list of events shown above.
Note: If errors occur on an opportunity product, you must return to the opportunity and fix the errors before
cloning.
If any opportunity products contain unique custom fields, you must null them out before cloning the opportunity.

Trigger.old contains a version of the objects before the specific update that fired the trigger. However, there is an
exception. When a record is updated and subsequently triggers a workflow rule field update, Trigger.old in the last

update trigger wont contain the version of the object immediately prior to the workflow update, but the object before the
initial update was made. For example, suppose an existing record has a number field with an initial value of 1. A user
updates this field to 10, and a workflow rule field update fires and increments it to 11. In the update trigger that fires after
the workflow field update, the field value of the object obtained from Trigger.old is the original value of 1, rather than
10, as would typically be the case.

Operations That Don't Invoke Triggers


Triggers are only invoked for data manipulation language (DML) operations that are initiated or processed by the Java
application server. Consequently, some system bulk operations don't currently invoke triggers. Some examples include:

Cascading delete operations. Records that did not initiate a delete don't cause trigger evaluation.
Cascading updates of child records that are reparented as a result of a merge operation
Mass campaign status changes
Mass division transfers
Mass address updates
Mass approval request transfers
Mass email actions
Modifying custom field data types
Renaming or replacing picklists
Managing price books
Changing a user's default division with the transfer division option checked
Changes to the following objects:
BrandTemplate
MassEmailTemplate
Folder

Update account triggers don't fire before or after a business account record type is changed to person account (or a person
account record type is changed to business account.)
Note: Inserts, updates, and deletes on person accounts fire account triggers, not contact triggers.

Before triggers associated with the following operations are only fired during lead conversion if validation and triggers for lead
conversion are enabled in the organization:

insert of accounts, contacts, and opportunities

94

Invoking Apex

Operations That Don't Invoke Triggers

update of accounts and contacts

Opportunity triggers are not fired when the account owner changes as a result of the associated opportunity's owner changing.
When you modify an opportunity product on an opportunity, or when an opportunity product schedule changes an opportunity
product, even if the opportunity product changes the opportunity, the before and after triggers and the validation rules
don't fire for the opportunity. However, roll-up summary fields do get updated, and workflow rules associated with the
opportunity do run.
The getContent and getContentAsPDF PageReference methods aren't allowed in triggers.
Note the following for the ContentVersion object:

Content pack operations involving the ContentVersion object, including slides and slide autorevision, don't invoke triggers.
Note: Content packs are revised when a slide inside of the pack is revised.

Values for the TagCsv and VersionData fields are only available in triggers if the request to create or update
ContentVersion records originates from the API.
You can't use before or after delete triggers with the ContentVersion object.

Things to consider about FeedItem and FeedComment triggers:

FeedItem and FeedComment objects don't support updates. Don't use before update or after update triggers.
FeedItem and FeedComment objects can't be undeleted. Don't use the after undelete trigger.
Only FeedItems of Type TextPost, LinkPost, and ContentPost can be inserted, and therefore invoke the before
or after insert trigger. User status updates don't cause the FeedItem triggers to fire.
While FeedPost objects were supported for API versions 18.0, 19.0, and 20.0, don't use any insert or delete triggers saved
against versions prior to 21.0.
For FeedItem the following fields are not available in the before insert trigger:
ContentSize
ContentType
In addition, the ContentData field is not available in any delete trigger.

For FeedComment before insert and after insert triggers, the fields of a ContentVersion associated with the
FeedComment (obtained through FeedComment.RelatedRecordId) are not available.
Apex code uses additional security when executing in a Chatter context. To post to a private group, the user running the
code must be a member of that group. If the running user isn't a member, you can set the CreatedById field to be a
member of the group in the FeedItem record.

95

Invoking Apex

Fields that Arent Available or Cant Be Updated in Triggers

Fields that Arent Available or Cant Be Updated in Triggers


QuestionDataCategorySelection Entity Not Available in After Insert Triggers
The after insert trigger that fires after inserting one ore more Question records doesnt have access to the
QuestionDataCategorySelection records that are associated with the inserted Questions. For example, the following
query doesnt return any results in an after insert trigger:
QuestionDataCategorySelection[] dcList =
[select Id,DataCategoryName from QuestionDataCategorySelection where ParentId IN :questions];

Fields Not Updateable in Before Triggers


Some field values are set during the system save operation, which occurs after before triggers have fired. As a result, these
fields cannot be modified or accurately detected in before insert or before update triggers. Some examples include:

Task.isClosed
Opportunity.amount*
Opportunity.ForecastCategory
Opportunity.isWon
Opportunity.isClosed
Contract.activatedDate
Contract.activatedById
Case.isClosed
Solution.isReviewed
Id (for all records)**
createdDate (for all records)**
lastUpdated (for all records)

* When Opportunity has no lineitems, Amount can be modified by a before trigger.


** Id and createdDate can be detected in before update triggers, but cannot be modified.

Trigger Exceptions
Triggers can be used to prevent DML operations from occurring by calling the addError() method on a record or field.
When used on Trigger.new records in insert and update triggers, and on Trigger.old records in delete triggers,
the custom error message is displayed in the application interface and logged.
Note: Users experience less of a delay in response time if errors are added to before triggers.

A subset of the records being processed can be marked with the addError() method:

If the trigger was spawned by a DML statement in Apex, any one error results in the entire operation rolling back. However,
the runtime engine still processes every record in the operation to compile a comprehensive list of errors.
If the trigger was spawned by a bulk DML call in the Force.com API, the runtime engine sets aside the bad records and
attempts to do a partial save of the records that did not generate errors. See Bulk DML Exception Handling on page 285.

If a trigger ever throws an unhandled exception, all records are marked with an error and no further processing takes place.

96

Invoking Apex

Trigger and Bulk Request Best Practices

Trigger and Bulk Request Best Practices


A common development pitfall is the assumption that trigger invocations never include more than one record. Apex triggers
are optimized to operate in bulk, which, by definition, requires developers to write logic that supports bulk operations.
This is an example of a flawed programming pattern. It assumes that only one record is pulled in during a trigger invocation.
While this might support most user interface events, it does not support bulk operations invoked through the SOAP API or
Visualforce.
trigger MileageTrigger on Mileage__c (before insert, before update) {
User c = [SELECT Id FROM User WHERE mileageid__c = Trigger.new[0].id];
}

This is another example of a flawed programming pattern. It assumes that less than 100 records are pulled in during a trigger
invocation. If more than 20 records are pulled into this request, the trigger would exceed the SOQL query limit of 100 SELECT
statements:
trigger MileageTrigger on Mileage__c (before insert, before update) {
for(mileage__c m : Trigger.new){
User c = [SELECT Id FROM user WHERE mileageid__c = m.Id];
}
}

For more information on governor limits, see Understanding Execution Governors and Limits on page 222.
This example demonstrates the correct pattern to support the bulk nature of triggers while respecting the governor limits:
Trigger MileageTrigger on Mileage__c (before insert, before update) {
Set<ID> ids = Trigger.new.keySet();
List<User> c = [SELECT Id FROM user WHERE mileageid__c in :ids];
}

This pattern respects the bulk nature of the trigger by passing the Trigger.new collection to a set, then using the set in a
single SOQL query. This pattern captures all incoming records within the request while limiting the number of SOQL queries.

Best Practices for Designing Bulk Programs


The following are the best practices for this design pattern:

Minimize the number of data manipulation language (DML) operations by adding records to collections and performing
DML operations against these collections.
Minimize the number of SOQL statements by preprocessing records and generating sets, which can be placed in single
SOQL statement used with the IN clause.

See Also:
What are the Limitations of Apex?

97

Invoking Apex

Apex Scheduler

Apex Scheduler
To invoke Apex classes to run at specific times, first implement the Schedulable interface for the class, then specify the
schedule using either the Schedule Apex page in the Salesforce user interface, or the System.schedule method.
For more information about the Schedule Apex page, see Scheduling Apex in the Salesforce online help.
Important: Salesforce only adds the process to the queue at the scheduled time. Actual execution may be delayed
based on service availability.
You can only have 25 classes scheduled at one time. You can evaluate your current count by viewing the Scheduled
Jobs page in Salesforce or programmatically using SOAP API to query the CronTrigger object.
Use extreme care if you are planning to schedule a class from a trigger. You must be able to guarantee that the trigger
will not add more scheduled classes than the 25 that are allowed. In particular, consider API bulk updates, import
wizards, mass record changes through the user interface, and all cases where more than one record can be updated at
a time.

Implementing the Schedulable Interface


To schedule an Apex class to run at regular intervals, first write an Apex class that implements the Salesforce-provided interface
Schedulable.
The scheduler runs as system: all classes are executed, whether the user has permission to execute the class or not. For more
information on setting class permissions, see Apex Class Security Overview in the Salesforce online help.
To monitor or stop the execution of a scheduled Apex job using the Salesforce user interface, click Your Name > Setup >
Monitoring > Scheduled Jobs. For more information, see Monitoring Scheduled Jobs in the Salesforce online help.
The Schedulable interface contains one method that must be implemented, execute.
global void execute(SchedulableContext sc){}

Use this method to instantiate the class you want to schedule.


Tip: Though it's possible to do additional processing in the execute method, we recommend that all processing
take place in a separate class.
The following example implements the Schedulable interface for a class called mergeNumbers:
global class scheduledMerge implements Schedulable{
global void execute(SchedulableContext SC) {
mergeNumbers M = new mergeNumbers();
}
}

The following example uses the System.Schedule method to implement the above class.
scheduledMerge m = new scheduledMerge();
String sch = '20 30 8 10 2 ?';
system.schedule('Merge Job', sch, m);

98

Invoking Apex

Apex Scheduler

You can also use the Schedulable interface with batch Apex classes. The following example implements the Schedulable
interface for a batch Apex class called batchable:
global class scheduledBatchable implements Schedulable{
global void execute(SchedulableContext sc) {
batchable b = new batchable();
database.executebatch(b);
}
}

Use the SchedulableContext object to keep track of the scheduled job once it's scheduled. The SchedulableContext method
getTriggerID returns the Id of the CronTrigger object associated with this scheduled job as a string. Use this method to
track the progress of the scheduled job.
To stop execution of a job that was scheduled, use the System.abortJob method with the ID returned by the.getTriggerID
method.

Testing the Apex Scheduler


The following is an example of how to test using the Apex scheduler.
The System.schedule method starts an asynchronous process. This means that when you test scheduled Apex, you must
ensure that the scheduled job is finished before testing against the results. Use the Test methods startTest and stopTest
around the System.schedule method to ensure it finishes before continuing your test. All asynchronous calls made after
the startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run
synchronously. If you dont include the System.schedule method within the startTest and stopTest methods, the
scheduled job executes at the end of your test method for Apex saved using Salesforce.com API version 25.0 and later, but
not in earlier versions.
This is the class to be tested.
global class TestScheduledApexFromTestMethod implements Schedulable {
// This test runs a scheduled job at midnight Sept. 3rd. 2022
public static String CRON_EXP = '0 0 0 3 9 ? 2022';
global void execute(SchedulableContext ctx) {
CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime
FROM CronTrigger WHERE Id = :ctx.getTriggerId()];
System.assertEquals(CRON_EXP, ct.CronExpression);
System.assertEquals(0, ct.TimesTriggered);
System.assertEquals('2022-09-03 00:00:00', String.valueOf(ct.NextFireTime));
Account a = [SELECT Id, Name FROM Account WHERE Name =
'testScheduledApexFromTestMethod'];
a.name = 'testScheduledApexFromTestMethodUpdated';
update a;
}
}

The following tests the above class:


@istest
class TestClass {
static testmethod void test() {
Test.startTest();

99

Invoking Apex

Apex Scheduler

Account a = new Account();


a.Name = 'testScheduledApexFromTestMethod';
insert a;
// Schedule the test job
String jobId = System.schedule('testBasicScheduledApex',
TestScheduledApexFromTestMethod.CRON_EXP,
new TestScheduledApexFromTestMethod());
// Get the information from the CronTrigger API object
CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered,
NextFireTime
FROM CronTrigger WHERE id = :jobId];
// Verify the expressions are the same
System.assertEquals(TestScheduledApexFromTestMethod.CRON_EXP,
ct.CronExpression);
// Verify the job has not run
System.assertEquals(0, ct.TimesTriggered);
// Verify the next time the job will run
System.assertEquals('2022-09-03 00:00:00',
String.valueOf(ct.NextFireTime));
System.assertNotEquals('testScheduledApexFromTestMethodUpdated',
[SELECT id, name FROM account WHERE id = :a.id].name);
Test.stopTest();
System.assertEquals('testScheduledApexFromTestMethodUpdated',
[SELECT Id, Name FROM Account WHERE Id = :a.Id].Name);
}
}

Using the System.Schedule Method


After you implement a class with the Schedulable interface, use the System.Schedule method to execute it. The scheduler
runs as system: all classes are executed, whether the user has permission to execute the class or not.
Note: Use extreme care if you are planning to schedule a class from a trigger. You must be able to guarantee that the
trigger will not add more scheduled classes than the 25 that are allowed. In particular, consider API bulk updates,
import wizards, mass record changes through the user interface, and all cases where more than one record can be
updated at a time.
The System.Schedule method takes three arguments: a name for the job, an expression used to represent the time and
date the job is scheduled to run, and the name of the class. This expression has the following syntax:
Seconds Minutes Hours Day_of_month Month Day_of_week optional_year

Note: Salesforce only adds the process to the queue at the scheduled time. Actual execution may be delayed based on
service availability.
The System.Schedule method uses the user's timezone for the basis of all schedules.
The following are the values for the expression:
Name

Values

Special Characters

Seconds

059

None

100

Invoking Apex

Apex Scheduler

Name

Values

Special Characters

Minutes

059

None

Hours

023

, - * /

Day_of_month

131

, - * ? / L W

Month

112 or the following:


JAN
FEB
MAR
APR
MAY
JUN
JUL
AUG
SEP
OCT
NOV
DEC

, - * /

Day_of_week

17 or the following:
SUN
MON
TUE
WED
THU
FRI
SAT

, - * ? / L #

optional_year

null or 19702099

, - * /

The special characters are defined as follows:


Special Character

Description

Delimits values. For example, use JAN, MAR, APR to specify more than one
month.

Specifies a range. For example, use JAN-MAR to specify more than one month.

Specifies all values. For example, if Month is specified as *, the job is scheduled
for every month.

Specifies no specific value. This is only available for Day_of_month and


Day_of_week, and is generally used when specifying a value for one and not
the other.

Specifies increments. The number before the slash specifies when the intervals
will begin, and the number after the slash is the interval amount. For example,

101

Invoking Apex

Special Character

Apex Scheduler

Description
if you specify 1/5 for Day_of_month, the Apex class runs every fifth day of the
month, starting on the first of the month.

Specifies the end of a range (last). This is only available for Day_of_month and
Day_of_week. When used with Day of month, L always means the last day
of the month, such as January 31, February 28 for leap years, and so on. When
used with Day_of_week by itself, it always means 7 or SAT. When used with
a Day_of_week value, it means the last of that type of day in the month. For
example, if you specify 2L, you are specifying the last Monday of the month.
Do not use a range of values with L as the results might be unexpected.

Specifies the nearest weekday (Monday-Friday) of the given day. This is only
available for Day_of_month. For example, if you specify 20W, and the 20th is
a Saturday, the class runs on the 19th. If you specify 1W, and the first is a
Saturday, the class does not run in the previous month, but on the third, which
is the following Monday.
Tip: Use the L and W together to specify the last weekday of the month.

Specifies the nth day of the month, in the format weekday#day_of_month.


This is only available for Day_of_week. The number before the # specifies
weekday (SUN-SAT). The number after the # specifies the day of the month.
For example, specifying 2#2 means the class runs on the second Monday of
every month.

The following are some examples of how to use the expression.


Expression

Description

0 0 13 * * ?

Class runs every day at 1 PM.

0 0 22 ? * 6L

Class runs the last Friday of every month at 10 PM.

0 0 10 ? * MON-FRI

Class runs Monday through Friday at 10 AM.

0 0 20 * * ? 2010

Class runs every day at 8 PM during the year 2010.

In the following example, the class proschedule implements the Schedulable interface. The class is scheduled to run at
8 AM, on the 13th of February.
proschedule p = new proschedule();
String sch = '0 0 8 13 2 ?';
system.schedule('One Time Pro', sch, p);

Apex Scheduler Best Practices and Limits

Salesforce only adds the process to the queue at the scheduled time. Actual execution may be delayed based on service
availability.

102

Invoking Apex

Anonymous Blocks

Use extreme care if you are planning to schedule a class from a trigger. You must be able to guarantee that the trigger will
not add more scheduled classes than the 25 that are allowed. In particular, consider API bulk updates, import wizards,
mass record changes through the user interface, and all cases where more than one record can be updated at a time.
Though it's possible to do additional processing in the execute method, we recommend that all processing take place in
a separate class.
You can only have 25 classes scheduled at one time. You can evaluate your current count by viewing the Scheduled Jobs
page in Salesforce or programmatically using SOAP API to query the CronTrigger object.
You can't use the getContent and getContentAsPDF PageReference methods in scheduled Apex.

Anonymous Blocks
An anonymous block is Apex code that does not get stored in the metadata, but that can be compiled and executed using one
of the following:

Developer Console
Force.com IDE
The executeAnonymous SOAP API call:
ExecuteAnonymousResult executeAnonymous(String code)

You can use anonymous blocks to quickly evaluate Apex on the fly, such as in the Developer Console or the Force.com IDE,
or to write code that changes dynamically at runtime. For example, you might write a client Web application that takes input
from a user, such as a name and address, and then uses an anonymous block of Apex to insert a contact with that name and
address into the database.
Note the following about the content of an anonymous block (for executeAnonymous, the code String):

Can include user-defined methods and exceptions.


User-defined methods cannot include the keyword static.
You do not have to manually commit any database changes.
If your Apex trigger completes successfully, any database changes are automatically committed. If your Apex trigger does
not complete successfully, any changes made to the database are rolled back.
Unlike classes and triggers, anonymous blocks execute as the current user and can fail to compile if the code violates the
user's object- and field-level permissions.
Do not have a scope other than local. For example, though it is legal to use the global access modifier, it has no meaning.
The scope of the method is limited to the anonymous block.

Even though a user-defined method can refer to itself or later methods without the need for forward declarations, variables
cannot be referenced before their actual declaration. In the following example, the Integer int must be declared while
myProcedure1 does not:
Integer int1 = 0;
void myProcedure1() {
myProcedure2();
}
void myProcedure2() {
int1++;
}

103

Invoking Apex

Apex in AJAX

myProcedure1();

The return result for anonymous blocks includes:

Status information for the compile and execute phases of the call, including any errors that occur
The debug log content, including the output of any calls to the System.debug method (see Understanding the Debug
Log on page 208)
The Apex stack trace of any uncaught code execution exceptions, including the class, method, and line number for each
call stack element

For more information on executeAnonymous(), see SOAP API and SOAP Headers for Apex. See also Using the Developer
Console and the Force.com IDE.

Apex in AJAX
The AJAX toolkit includes built-in support for invoking Apex through anonymous blocks or public webService methods.
To do so, include the following lines in your AJAX code:
<script src="/soap/ajax/15.0/connection.js" type="text/javascript"></script>
<script src="/soap/ajax/15.0/apex.js" type="text/javascript"></script>

Note: For AJAX buttons, use the alternate forms of these includes.

To invoke Apex, use one of the following two methods:

Execute anonymously via sforce.apex.executeAnonymous (script). This method returns a result similar to the
API's result type, but as a JavaScript structure.
Use a class WSDL. For example, you can call the following Apex class:
global class myClass {
webService static Id makeContact(String lastName, Account a) {
Contact c = new Contact(LastName = lastName, AccountId = a.Id);
return c.id;
}
}

By using the following JavaScript code:


var account = sforce.sObject("Account");
var id = sforce.apex.execute("myClass","makeContact",
{lastName:"Smith",
a:account});

The execute method takes primitive data types, sObjects, and lists of primitives or sObjects.
To call a webService method with no parameters, use {} as the third parameter for sforce.apex.execute. For example,
to call the following Apex class:
global class myClass{
webService static String getContextUserName() {

104

Invoking Apex

Apex in AJAX

return UserInfo.getFirstName();
}
}

Use the following JavaScript code:


var contextUser = sforce.apex.execute("myClass", "getContextUserName", {});

Note: If a namespace has been defined for your organization, you must include it in the JavaScript code when you
invoke the class. For example, to call the above class, the JavaScript code from above would be rewritten as follows:
var contextUser = sforce.apex.execute("myNamespace.myClass", "getContextUserName",
{});

To verify whether your organization has a namespace, log in to your Salesforce organization and navigate to Your
Name > Setup > Create > Packages. If a namespace is defined, it is listed under Developer Settings.
Both examples result in native JavaScript values that represent the return type of the methods.
Use the following line to display a popup window with debugging information:
sforce.debug.trace=true;

105

Chapter 4
Classes, Objects, and Interfaces
In this chapter ...

Understanding Classes
Interfaces and Extending Classes
Keywords
Annotations
Classes and Casting
Differences Between Apex Classes
and Java Classes
Class Definition Creation
Class Security
Enforcing Object and Field
Permissions
Namespace Prefix
Version Settings

A class is a template or blueprint from which Apex objects are created. Classes
consist of other classes, user-defined methods, variables, exception types, and
static initialization code. They are stored in the application under Your Name
> Setup > Develop > Apex Classes.
Once successfully saved, class methods or variables can be invoked by other Apex
code, or through the SOAP API (or AJAX Toolkit) for methods that have been
designated with the webService keyword.
In most cases, the class concepts described here are modeled on their counterparts
in Java, and can be quickly understood by those who are familiar with them.

Understanding Classesmore about creating classes in Apex


Interfaces and Extending Classesinformation about interfaces
Keywords and Annotationsadditional modifiers for classes, methods or
variables
Classes and Castingassigning a class of one data type to another
Differences Between Apex Classes and Java Classeshow Apex and Java
differ
Class Definition Creation and Class Securitycreating a class in the
Salesforce user interface as well as enabling users to access a class
Namespace Prefix and Version Settingsusing a namespace prefix and
versioning Apex classes

106

Classes, Objects, and Interfaces

Understanding Classes

Understanding Classes
As in Java, you can create classes in Apex. A class is a template or blueprint from which objects are created. An object is an
instance of a class. For example, the PurchaseOrder class describes an entire purchase order, and everything that you can
do with a purchase order. An instance of the PurchaseOrder class is a specific purchase order that you send or receive.
All objects have state and behavior, that is, things that an object knows about itself, and things that an object can do. The state
of a PurchaseOrder objectwhat it knowsincludes the user who sent it, the date and time it was created, and whether it
was flagged as important. The behavior of a PurchaseOrder objectwhat it can doincludes checking inventory, shipping
a product, or notifying a customer.
A class can contain variables and methods. Variables are used to specify the state of an object, such as the object's Name or
Type. Since these variables are associated with a class and are members of it, they are commonly referred to as member variables.
Methods are used to control behavior, such as getOtherQuotes or copyLineItems.
An interface is like a class in which none of the methods have been implementedthe method signatures are there, but the
body of each method is empty. To use an interface, another class must implement it by providing a body for all of the methods
contained in the interface.
For more general information on classes, objects, and interfaces, see
http://java.sun.com/docs/books/tutorial/java/concepts/index.html

Defining Apex Classes


In Apex, you can define top-level classes (also called outer classes) as well as inner classes, that is, a class defined within another
class. You can only have inner classes one level deep. For example:
public class myOuterClass {
// Additional myOuterClass code here
class myInnerClass {
// myInnerClass code here
}
}

To define a class, specify the following:


1. Access modifiers:

You must use one of the access modifiers (such as public or global) in the declaration of a top-level class.
You do not have to use an access modifier in the declaration of an inner class.

2. Optional definition modifiers (such as virtual, abstract, and so on)


3. Required: The keyword class followed by the name of the class
4. Optional extensions and/or implementations
Use the following syntax for defining classes:
private | public | global
[virtual | abstract | with sharing | without sharing | (none)]
class ClassName [implements InterfaceNameList | (none)] [extends ClassName | (none)]
{
// The body of the class
}

107

Classes, Objects, and Interfaces

Extended Class Example

The private access modifier declares that this class is only known locally, that is, only by this section of code. This is the
default access for inner classesthat is, if you don't specify an access modifier for an inner class, it is considered private.
This keyword can only be used with inner classes.
The public access modifier declares that this class is visible in your application or namespace.
The global access modifier declares that this class is known by all Apex code everywhere. All classes that contain methods
defined with the webService keyword must be declared as global. If a method or inner class is declared as global,
the outer, top-level class must also be defined as global.
The with sharing and without sharing keywords specify the sharing mode for this class. For more information,
see Using the with sharing or without sharing Keywords on page 131.
The virtual definition modifier declares that this class allows extension and overrides. You cannot override a method
with the override keyword unless the class has been defined as virtual.
The abstract definition modifier declares that this class contains abstract methods, that is, methods that only have their
signature declared and no body defined.
Note: You cannot add an abstract method to a class after the class has been uploaded in a Managed - Released package
version. If the class in the Managed - Released package is virtual, the method that you can add to it must also be virtual
and must have an implementation. For more information about managed packages, see Developing Apex in Managed
Packages on page 228.

A class can implement multiple interfaces, but only extend one existing class. This restriction means that Apex does not support
multiple inheritance. The interface names in the list are separated by commas. For more information about interfaces, see
Interfaces and Extending Classes on page 122.
For more information about method and variable access modifiers, see Access Modifiers on page 116.

Extended Class Example


The following is an extended example of a class, showing all the features of Apex classes. The keywords and concepts introduced
in the example are explained in more detail throughout this chapter.
// Top-level (outer) class must be public or global (usually public unless they contain
// a Web Service, then they must be global)
public class OuterClass {
// Static final variable (constant) outer class level only
private static final Integer MY_INT;
// Non-final static variable - use this to communicate state across triggers
// within a single request)
public static String sharedState;
// Static method - outer class level only
public static Integer getInt() { return MY_INT; }
// Static initialization (can be included where the variable is defined)
static {
MY_INT = 2;
}
// Member variable for outer class
private final String m;
// Instance initialization block - can be done where the variable is declared,
// or in a constructor
{
m = 'a';

108

Classes, Objects, and Interfaces

Extended Class Example

}
// Because no constructor is explicitly defined in this outer class, an implicit,
// no-argument, public constructor exists
// Inner interface
public virtual interface MyInterface {
// No access modifier is necessary for interface methods - these are always
// public or global depending on the interface visibility
void myMethod();
}
// Interface extension
interface MySecondInterface extends MyInterface {
Integer method2(Integer i);
}
// Inner class - because it is virtual it can be extended.
// This class implements an interface that, in turn, extends another interface.
// Consequently the class must implement all methods.
public virtual class InnerClass implements MySecondInterface {
// Inner member variables
private final String s;
private final String s2;
// Inner instance initialization block (this code could be located above)
{
this.s = 'x';
}
// Inline initialization (happens after the block above executes)
private final Integer i = s.length();
// Explicit no argument constructor
InnerClass() {
// This invokes another constructor that is defined later
this('none');
}
// Constructor that assigns a final variable value
public InnerClass(String s2) {
this.s2 = s2;
}
// Instance method that implements a method from MyInterface.
// Because it is declared virtual it can be overridden by a subclass.
public virtual void myMethod() { /* does nothing */ }
// Implementation of the second interface method above.
// This method references member variables (with and without the "this" prefix)
public Integer method2(Integer i) { return this.i + s.length(); }
}
// Abstract class (that subclasses the class above). No constructor is needed since
// parent class has a no-argument constructor
public abstract class AbstractChildClass extends InnerClass {
// Override the parent class method with this signature.
// Must use the override keyword
public override void myMethod() { /* do something else */ }
// Same name as parent class method, but different signature.
// This is a different method (displaying polymorphism) so it does not need
// to use the override keyword
protected void method2() {}

109

Classes, Objects, and Interfaces

Extended Class Example

// Abstract method - subclasses of this class must implement this method


abstract Integer abstractMethod();
}
// Complete the abstract class by implementing its abstract method
public class ConcreteChildClass extends AbstractChildClass {
// Here we expand the visibility of the parent method - note that visibility
// cannot be restricted by a sub-class
public override Integer abstractMethod() { return 5; }
}
// A second sub-class of the original InnerClass
public class AnotherChildClass extends InnerClass {
AnotherChildClass(String s) {
// Explicitly invoke a different super constructor than one with no arguments
super(s);
}
}
// Exception inner class
public virtual class MyException extends Exception {
// Exception class member variable
public Double d;
// Exception class constructor
MyException(Double d) {
this.d = d;
}
// Exception class method, marked as protected
protected void doIt() {}
}
// Exception classes can be abstract and implement interfaces
public abstract class MySecondException extends Exception implements MyInterface {
}
}

This code example illustrates:

A top-level class definition (also called an outer class)


Static variables and static methods in the top-level class, as well as static initialization code blocks
Member variables and methods for the top-level class
Classes with no user-defined constructor these have an implicit, no-argument constructor
An interface definition in the top-level class
An interface that extends another interface
Inner class definitions (one level deep) within a top-level class
A class that implements an interface (and, therefore, its associated sub-interface) by implementing public versions of the
method signatures
An inner class constructor definition and invocation
An inner class member variable and a reference to it using the this keyword (with no arguments)
An inner class constructor that uses the this keyword (with arguments) to invoke a different constructor
Initialization code outside of constructors both where variables are defined, as well as with anonymous blocks in curly
braces ({}). Note that these execute with every construction in the order they appear in the file, as with Java.
Class extension and an abstract class
Methods that override base class methods (which must be declared virtual)

110

Classes, Objects, and Interfaces

Declaring Class Variables

The override keyword for methods that override subclass methods


Abstract methods and their implementation by concrete sub-classes
The protected access modifier
Exceptions as first class objects with members, methods, and constructors

This example shows how the class above can be called by other Apex code:
// Construct an instance of an inner concrete class, with a user-defined constructor
OuterClass.InnerClass ic = new OuterClass.InnerClass('x');
// Call user-defined methods in the class
System.assertEquals(2, ic.method2(1));
// Define a variable with an interface data type, and assign it a value that is of
// a type that implements that interface
OuterClass.MyInterface mi = ic;
// Use instanceof and casting as usual
OuterClass.InnerClass ic2 = mi instanceof OuterClass.InnerClass ?
(OuterClass.InnerClass)mi : null;
System.assert(ic2 != null);
// Construct the outer type
OuterClass o = new OuterClass();
System.assertEquals(2, OuterClass.getInt());
// Construct instances of abstract class children
System.assertEquals(5, new OuterClass.ConcreteChildClass().abstractMethod());
// Illegal - cannot construct an abstract class
// new OuterClass.AbstractChildClass();
// Illegal cannot access a static method through an instance
// o.getInt();
// Illegal - cannot call protected method externally
// new OuterClass.ConcreteChildClass().method2();

This code example illustrates:

Construction of the outer class


Construction of an inner class and the declaration of an inner interface type
A variable declared as an interface type can be assigned an instance of a class that implements that interface
Casting an interface variable to be a class type that implements that interface (after verifying this using the instanceof
operator)

Declaring Class Variables


To declare a variable, specify the following:

Optional: Modifiers, such as public or final, as well as static.


Required: The data type of the variable, such as String or Boolean.
Required: The name of the variable.
Optional: The value of the variable.

111

Classes, Objects, and Interfaces

Defining Class Methods

Use the following syntax when defining a variable:


[public | private | protected | global | final] [static] data_type variable_name
[= value]

For example:
private static final Integer MY_INT;
private final Integer i = 1;

Defining Class Methods


To define a method, specify the following:

Optional: Modifiers, such as public or protected.


Required: The data type of the value returned by the method, such as String or Integer. Use void if the method does not
return a value.
Required: A list of input parameters for the method, separated by commas, each preceded by its data type, and enclosed
in parentheses (). If there are no parameters, use a set of empty parentheses. A method can only have 32 input parameters.
Required: The body of the method, enclosed in braces {}. All the code for the method, including any local variable
declarations, is contained here.

Use the following syntax when defining a method:


(public | private | protected | global ) [override] [static] data_type method_name
(input parameters)
{
// The body of the method
}

Note: You can only use override to override methods in classes that have been defined as virtual.

For example:
public static Integer getInt() {
return MY_INT;
}

As in Java, methods that return values can also be run as a statement if their results are not assigned to another variable.
Note that user-defined methods:

Can be used anywhere that system methods are used.


Can be recursive.
Can have side effects, such as DML insert statements that initialize sObject record IDs. See Apex Data Manipulation
Language (DML) Operations on page 264.
Can refer to themselves or to methods defined later in the same class or anonymous block. Apex parses methods in two
phases, so forward declarations are not needed.
Can be polymorphic. For example, a method named foo can be implemented in two ways, one with a single Integer
parameter and one with two Integer parameters. Depending on whether the method is called with one or two Integers,

112

Classes, Objects, and Interfaces

Defining Class Methods

the Apex parser selects the appropriate implementation to execute. If the parser cannot find an exact match, it then seeks
an approximate match using type coercion rules. For more information on data conversion, see Understanding Rules of
Conversion on page 52.
Note: If the parser finds multiple approximate matches, a parse-time exception is generated.

When using void methods that have side effects, user-defined methods are typically executed as stand-alone procedure
statements in Apex code. For example:

System.debug('Here is a note for the log.');

Can have statements where the return values are run as a statement if their results are not assigned to another variable.
This is the same as in Java.

Passing Method Arguments By Value


In Apex, all primitive data type arguments, such as Integer or String, are passed into methods by value. This means that any
changes to the arguments exist only within the scope of the method. When the method returns, the changes to the arguments
are lost.
Non-primitive data type arguments, such as sObjects, are also passed into methods by value. This means that when the method
returns, the passed-in argument still references the same object as before the method call and can't be changed to point to
another object. However, the values of the object's fields can be changed in the method.
The following are examples of passing primitive and non-primitive data type arguments into methods.
Example: Passing Primitive Data Type Arguments
This example shows how a primitive argument of type String is passed by value into another method. The
debugStatusMessage method in this example creates a String variable, msg, and assigns it a value. It then passes this
variable as an argument to another method, which modifies the value of this String. However, since String is a primitive type,
it is passed by value, and when the method returns, the value of the original variable, msg, is unchanged. An assert statement
verifies that the value of msg is still the old value.
public class PassPrimitiveTypeExample {
public static void debugStatusMessage() {
String msg = 'Original value';
processString(msg);
// The value of the msg variable didn't
// change; it is still the old value.
System.assertEquals(msg, 'Original value');
}
public static void processString(String s) {
s = 'Modified value';
}
}

Example: Passing Non-Primitive Data Type Arguments


This example shows how a List argument is passed by value into another method and can be modified. It also shows that the
List argument cant be modified to point to another List object. First, the createTemperatureHistory method creates
a variable, fillMe, that is a List of Integers and passes it to a method. The called method fills this list with Integer values
representing rounded temperature values. When the method returns, an assert verifies that the contents of the original List
variable has changed and now contains five values. Next, the example creates a second List variable, createMe, and passes it
to another method. The called method assigns the passed-in argument to a newly created List that contains new Integer values.

113

Classes, Objects, and Interfaces

Using Constructors

When the method returns, the original createMe variable doesnt point to the new List but still points to the original List,
which is empty. An assert verifies that createMe contains no values.
public class PassNonPrimitiveTypeExample {
public static void createTemperatureHistory() {
List<Integer> fillMe = new List<Integer>();
reference(fillMe);
// The list is modified and contains five items
// as expected.
System.assertEquals(fillMe.size(),5);
List<Integer> createMe = new List<Integer>();
referenceNew(createMe);
// The list is not modified because it still points
// to the original list, not the new list
// that the method created.
System.assertEquals(createMe.size(),0);
}
public static void reference(List<Integer> m) {
// Add rounded temperatures for the last five days.
m.add(70);
m.add(68);
m.add(75);
m.add(80);
m.add(82);
}
public static void referenceNew(List<Integer> m) {
// Assign argument to a new List of
// five temperature values.
m = new List<Integer>{55, 59, 62, 60, 63};
}
}

Using Constructors
A constructor is code that is invoked when an object is created from the class blueprint. You do not need to write a constructor
for every class. If a class does not have a user-defined constructor, an implicit, no-argument, public one is used.
The syntax for a constructor is similar to a method, but it differs from a method definition in that it never has an explicit return
type and it is not inherited by the object created from it.
After you write the constructor for a class, you must use the new keyword in order to instantiate an object from that class,
using that constructor. For example, using the following class:
public class TestObject {
// The no argument constructor
public TestObject() {
// more code here
}
}

A new object of this type can be instantiated with the following code:
TestObject myTest = new TestObject();

114

Classes, Objects, and Interfaces

Using Constructors

If you write a constructor that takes arguments, you can then use that constructor to create an object using those arguments.
If you create a constructor that takes arguments, and you still want to use a no-argument constructor, you must include one
in your code. Once you create a constructor for a class, you no longer have access to the default, no-argument public constructor.
You must create your own.
In Apex, a constructor can be overloaded, that is, there can be more than one constructor for a class, each having different
parameters. The following example illustrates a class with two constructors: one with no arguments and one that takes a simple
Integer argument. It also illustrates how one constructor calls another constructor using the this(...) syntax, also know as
constructor chaining.
public class TestObject2 {
private static final Integer DEFAULT_SIZE = 10;
Integer size;
//Constructor with no arguments
public TestObject2() {
this(DEFAULT_SIZE); // Using this(...) calls the one argument constructor
}
// Constructor with one argument
public TestObject2(Integer ObjectSize) {
size = ObjectSize;
}
}

New objects of this type can be instantiated with the following code:
TestObject2 myObject1 = new TestObject2(42);
TestObject2 myObject2 = new TestObject2();

Every constructor that you create for a class must have a different argument list. In the following example, all of the constructors
are possible:
public class Leads {
// First a no-argument constructor
public Leads () {}
// A constructor with one argument
public Leads (Boolean call) {}
// A constructor with two arguments
public Leads (String email, Boolean call) {}
// Though this constructor has the same arguments as the
// one above, they are in a different order, so this is legal
public Leads (Boolean call, String email) {}
}

When you define a new class, you are defining a new data type. You can use class name in any place you can use other data
type names, such as String, Boolean, or Account. If you define a variable whose type is a class, any object you assign to it must
be an instance of that class or subclass.

115

Classes, Objects, and Interfaces

Access Modifiers

Access Modifiers
Apex allows you to use the private, protected, public, and global access modifiers when defining methods and
variables.
While triggers and anonymous blocks can also use these access modifiers, they are not as useful in smaller portions of Apex.
For example, declaring a method as global in an anonymous block does not enable you to call it from outside of that code.
For more information on class access modifiers, see Defining Apex Classes on page 107.
Note: Interface methods have no access modifiers. They are always global. For more information, see Interfaces and
Extending Classes on page 122.
By default, a method or variable is visible only to the Apex code within the defining class. You must explicitly specify a method
or variable as public in order for it to be available to other classes in the same application namespace (see Namespace Prefix
on page 149). You can change the level of visibility by using the following access modifiers:
private

This is the default, and means that the method or variable is accessible only within the Apex class in which it is defined.
If you do not specify an access modifier, the method or variable is private.
protected

This means that the method or variable is visible to any inner classes in the defining Apex class. You can only use this
access modifier for instance methods and member variables. Note that it is strictly more permissive than the default
(private) setting, just like Java.
public

This means the method or variable can be used by any Apex in this application or namespace.
Note: In Apex, the public access modifier is not the same as it is in Java. This was done to discourage joining
applications, to keep the code for each application separate. In Apex, if you want to make something public like
it is in Java, you need to use the global access modifier.

global

This means the method or variable can be used by any Apex code that has access to the class, not just the Apex code in
the same application. This access modifier should be used for any method that needs to be referenced outside of the
application, either in the SOAP API or by other Apex code. If you declare a method or variable as global, you must
also declare the class that contains it as global.
Note: We recommend using the global access modifier rarely, if at all. Cross-application dependencies are
difficult to maintain.

To use the private, protected, public, or global access modifiers, use the following syntax:
[(none)|private|protected|public|global] declaration

For example:
private string s1 = '1';

116

Classes, Objects, and Interfaces

Static and Instance

public string gets1() {


return this.s1;
}

Static and Instance


In Apex, you can have static methods, variables, and initialization code. Apex classes cant be static. You can also have instance
methods, member variables, and initialization code (which have no modifier), and local variables:

Static methods, variables, or initialization code are associated with a class, and are only allowed in outer classes. When you
declare a method or variable as static, it's initialized only once when a class is loaded. Static variables aren't transmitted
as part of the view state for a Visualforce page.
Instance methods, member variables, and initialization code are associated with a particular object and have no definition
modifier. When you declare instance methods, member variables, or initialization code, an instance of that item is created
with every object instantiated from the class.
Local variables are associated with the block of code in which they are declared. All local variables should be initialized
before they are used.

The following is an example of a local variable whose scope is the duration of the if code block:
Boolean myCondition = true;
if (myCondition) {
integer localVariable = 10;
}

Using Static Methods and Variables


You can only use static methods and variables with outer classes. Inner classes have no static methods or variables. A static
method or variable does not require an instance of the class in order to run.
All static member variables in a class are initialized before any object of the class is created. This includes any static initialization
code blocks. All of these are run in the order in which they appear in the class.
Static methods are generally used as utility methods and never depend on a particular instance member variable value. Because
a static method is only associated with a class, it cannot access any instance member variable values of its class.
Static variables are only static within the scope of the request. They are not static across the server, or across the entire
organization.
Use static variables to store information that is shared within the confines of the class. All instances of the same class share a
single copy of the static variables. For example, all triggers that are spawned by the same request can communicate with each
other by viewing and updating static variables in a related class. A recursive trigger might use the value of a class variable to
determine when to exit the recursion.
Suppose you had the following class:
public class p {
public static boolean firstRun = true;
}

A trigger that uses this class could then selectively fail the first run of the trigger:
trigger t1 on Account (before delete, after delete, after undelete) {
if(Trigger.isBefore){

117

Classes, Objects, and Interfaces

Static and Instance

if(Trigger.isDelete){
if(p.firstRun){
Trigger.old[0].addError('Before Account Delete Error');
p.firstRun=false;
}
}
}
}

Class static variables cannot be accessed through an instance of that class. So if class C has a static variable S, and x is an
instance of C, then x.S is not a legal expression.
The same is true for instance methods: if M() is a static method then x.M() is not legal. Instead, your code should refer to
those static identifiers using the class: C.S and C.M().
If a local variable is named the same as the class name, these static methods and variables are hidden.
Inner classes behave like static Java inner classes, but do not require the static keyword. Inner classes can have instance
member variables like outer classes, but there is no implicit pointer to an instance of the outer class (using the this keyword).
Note: For Apex saved using Salesforce.com API version 20.0 or earlier, if an API call causes a trigger to fire, the
batch of 200 records to process is further split into batches of 100 records. For Apex saved using Salesforce.com API
version 21.0 and later, no further splits of API batches occur. Note that static variable values are reset between batches,
but governor limits are not. Do not use static variables to track state information between batches.

Using Instance Methods and Variables


Instance methods and member variables are used by an instance of a class, that is, by an object. Instance member variables are
declared inside a class, but not within a method. Instance methods usually use instance member variables to affect the behavior
of the method.
Suppose you wanted to have a class that collects two dimensional points and plot them on a graph. The following skeleton
class illustrates this, making use of member variables to hold the list of points and an inner class to manage the two-dimensional
list of points.
public class Plotter {
// This inner class manages the points
class Point {
Double x;
Double y;
Point(Double x, Double y) {
this.x = x;
this.y = y;
}
Double getXCoordinate() {
return x;
}
Double getYCoordinate() {
return y;
}
}
List<Point> points = new List<Point>();
public void plot(Double x, Double y) {
points.add(new Point(x, y));
}

118

Classes, Objects, and Interfaces

Static and Instance

// The following method takes the list of points and does something with them
public void render() {
}
}

Using Initialization Code


Instance initialization code is a block of code in the following form that is defined in a class:
{
//code body
}

The instance initialization code in a class is executed every time an object is instantiated from that class. These code blocks
run before the constructor.
If you do not want to write your own constructor for a class, you can use an instance initialization code block to initialize
instance variables. However, most of the time you should either give the variable a default value or use the body of a constructor
to do initialization and not use instance initialization code.
Static initialization code is a block of code preceded with the keyword static:
static {
//code body
}

Similar to other static code, a static initialization code block is only initialized once on the first use of the class.
A class can have any number of either static or instance initialization code blocks. They can appear anywhere in the code body.
The code blocks are executed in the order in which they appear in the file, the same as in Java.
You can use static initialization code to initialize static final variables and to declare any information that is static, such as a
map of values. For example:
public class MyClass {
class RGB {
Integer red;
Integer green;
Integer blue;
RGB(Integer red, Integer green, Integer blue) {
this.red = red;
this.green = green;
this.blue = blue;
}
}
static Map<String, RGB> colorMap = new Map<String, RGB>();
static {
colorMap.put('red', new RGB(255, 0, 0));
colorMap.put('cyan', new RGB(0, 255, 255));
colorMap.put('magenta', new RGB(255, 0, 255));

119

Classes, Objects, and Interfaces

Apex Properties

}
}

Apex Properties
An Apex property is similar to a variable, however, you can do additional things in your code to a property value before it is
accessed or returned. Properties can be used in many different ways: they can validate data before a change is made; they can
prompt an action when data is changed, such as altering the value of other member variables; or they can expose data that is
retrieved from some other source, such as another class.
Property definitions include one or two code blocks, representing a get accessor and a set accessor:
The code in a get accessor executes when the property is read.
The code in a set accessor executes when the property is assigned a new value.

A property with only a get accessor is considered read-only. A property with only a set accessor is considered write-only. A
property with both accessors is read-write.
To declare a property, use the following syntax in the body of a class:
Public class BasicClass {
// Property declaration
access_modifier return_type property_name {
get {
//Get accessor code block
}
set {
//Set accessor code block
}
}
}

Where:

access_modifier is the access modifier for the property. All modifiers that can be applied to variables can also be applied
to properties. These include: public, private, global, protected, static, virtual, abstract, override and
transient. For more information on access modifiers, see Access Modifiers on page 116.

return_type is the type of the property, such as Integer, Double, sObject, and so on. For more information, see Data

Types on page 36.


property_name is the name of the property

For example, the following class defines a property named prop. The property is public. The property returns an integer data
type.
public class BasicProperty {
public integer prop {
get { return prop; }
set { prop = value; }
}
}

120

Classes, Objects, and Interfaces

Apex Properties

The following code segment calls the class above, exercising the get and set accessors:
BasicProperty bp = new BasicProperty();
bp.prop = 5;
// Calls set accessor
System.assert(bp.prop == 5);
// Calls get accessor

Note the following:

The body of the get accessor is similar to that of a method. It must return a value of the property type. Executing the get
accessor is the same as reading the value of the variable.
The get accessor must end in a return statement.
We recommend that your get accessor should not change the state of the object that it is defined on.
The set accessor is similar to a method whose return type is void.
When you assign a value to the property, the set accessor is invoked with an argument that provides the new value.
When the set accessor is invoked, the system passes an implicit argument to the setter called value of the same data type
as the property.
Properties cannot be defined on interface.
Apex properties are based on their counterparts in C#, with the following differences:
Properties provide storage for values directly. You do not need to create supporting members for storing values.
It is possible to create automatic properties in Apex. For more information, see Using Automatic Properties on page
121.

Using Automatic Properties


Properties do not require additional code in their get or set accessor code blocks. Instead, you can leave get and set accessor
code blocks empty to define an automatic property. Automatic properties allow you to write more compact code that is easier
to debug and maintain. They can be declared as read-only, read-write, or write-only. The following example creates three
automatic properties:
public class AutomaticProperty {
public integer MyReadOnlyProp { get; }
public double MyReadWriteProp { get; set; }
public string MyWriteOnlyProp { set; }
}

The following code segment exercises these properties:


AutomaticProperty ap = new AutomaticProperty();
ap.MyReadOnlyProp = 5;
// This produces a compile error: not writable
ap.MyReadWriteProp = 5;
// No error
System.assert(MyWriteOnlyProp == 5);
// This produces a compile error: not readable

Using Static Properties


When a property is declared as static, the property's accessor methods execute in a static context. This means that the
accessors do not have access to non-static member variables defined in the class. The following example creates a class with
both static and instance properties:
public class StaticProperty {
public static integer StaticMember;
public integer NonStaticMember;
public static integer MyGoodStaticProp {
get{return MyGoodStaticProp;}

121

Classes, Objects, and Interfaces

Interfaces and Extending Classes

}
// The following produces a system error
// public static integer MyBadStaticProp { return NonStaticMember; }
public integer MyGoodNonStaticProp {
get{return NonStaticMember;}
}
}

The following code segment calls the static and instance properties:
StaticProperty sp = new StaticProperty();
// The following produces a system error: a static variable cannot be
// accessed through an object instance
// sp.MyGoodStaticProp = 5;
// The following does not produce an error
StaticProperty.MyGoodStaticProp = 5;

Using Access Modifiers on Property Accessors


Property accessors can be defined with their own access modifiers. If an accessor includes its own access modifier, this modifier
overrides the access modifier of the property. The access modifier of an individual accessor must be more restrictive than the
access modifier on the property itself. For example, if the property has been defined as public, the individual accessor cannot
be defined as global. The following class definition shows additional examples:
global virtual class PropertyVisibility {
// X is private for read and public for write
public integer X { private get; set; }
// Y can be globally read but only written within a class
global integer Y { get; public set; }
// Z can be read within the class but only subclasses can set it
public integer Z { get; protected set; }
}

Interfaces and Extending Classes


An interface is like a class in which none of the methods have been implementedthe method signatures are there, but the
body of each method is empty. To use an interface, another class must implement it by providing a body for all of the methods
contained in the interface.
Interfaces can provide a layer of abstraction to your code. They separate the specific implementation of a method from the
declaration for that method. This way you can have different implementations of a method based on your specific application.
Defining an interface is similar to defining a new class. For example, a company might have two types of purchase orders,
ones that come from customers, and others that come from their employees. Both are a type of purchase order. Suppose you
needed a method to provide a discount. The amount of the discount can depend on the type of purchase order.
You can model the general concept of a purchase order as an interface and have specific implementations for customers and
employees. In the following example the focus is only on the discount aspect of a purchase order.
public class PurchaseOrders {
// An interface that defines what a purchase order looks like in general
public interface PurchaseOrder {
// All other functionality excluded

122

Classes, Objects, and Interfaces

Parameterized Typing and Interfaces

Double discount();
}
// One implementation of the interface for customers
public virtual class CustomerPurchaseOrder implements PurchaseOrder {
public virtual Double discount() {
return .05; // Flat 5% discount
}
}
// Employee purchase order extends Customer purchase order, but with a
// different discount
public class EmployeePurchaseOrder extends CustomerPurchaseOrder{
public override Double discount() {
return .10; // Its worth it being an employee! 10% discount
}
}
}

Note the following about the above example:

The interface PurchaseOrder is defined as a general prototype. Methods defined within an interface have no access
modifiers and contain just their signature.
The CustomerPurchaseOrder class implements this interface; therefore, it must provide a definition for the discount
method. As with Java, any class that implements an interface must define all of the methods contained in the interface.
The employee version of the purchase order extends the customer version. A class extends another class using the keyword
extends. A class can only extend one other class, but it can implement more than one interface.

When you define a new interface, you are defining a new data type. You can use an interface name in any place you can use
another data type name. If you define a variable whose type is an interface, any object you assign to it must be an instance of
a class that implements the interface, or a sub-interface data type.
An interface can extend another interface. As with classes, when an interface extends another interface, all the methods and
properties of the extended interface are available to the extending interface.
See also Classes and Casting on page 142.
You cannot add a method to an interface after the class has been uploaded in a Managed - Released package version. For more
information about managed packages, see Developing Apex in Managed Packages on page 228.

Parameterized Typing and Interfaces


Apex, in general, is a statically-typed programming language, which means users must specify the data type for a variable
before that variable can be used. For example, the following is legal in Apex:
Integer x = 1;

The following is not legal if x has not been defined earlier:


x = 1;

Lists, maps and sets are parameterized in Apex: they take any data type Apex supports for them as an argument. That data
type must be replaced with an actual data type upon construction of the list, map or set. For example:
List<String> myList = new List<String>();

123

Classes, Objects, and Interfaces

Parameterized Typing and Interfaces

Parameterized typing allows interfaces to be implemented with generic data type parameters that are replaced with actual data
types upon construction.
The following gives an example of how the syntax of a parameterized interface works. In this example, the interface Pair has
two type variables, T and U. A type variable can be used like a regular type in the body of the interface.
public virtual interface Pair<T, U> {
T getFirst();
U getSecond();
void setFirst(T val);
void setSecond(U val);
Pair<U, T> swap();
}

The following interface DoubleUp extends the Pair interface. It uses the type variable T:
public interface DoubleUp<T> extends Pair<T, T> {}

Tip: Notice that Pair must be defined as virtual for it to be extended by DoubleUp.

Implementing Parameterized Interfaces


A class that implements a parameterized interface must pass data types in as arguments to the interface's type parameters.
public class StringPair implements DoubleUp<String> {
private String s1;
private String s2;
public StringPair(String s1, String s2) {
this.s1 = s1;
this.s2 = s2;
}
public String getFirst() { return this.s1; }
public String getSecond() { return this.s2; }
public void setFirst(String val) { this.s1 = val; }
public void setSecond(String val) { this.s2 = val; }
public Pair<String, String> swap() {
return new StringPair(this.s2, this.s1);
}
}

Type variables can never appear outside an interface declaration, such as in a class. However, fully instantiated types, such as
Pair<String, String> are allowed anywhere in Apex that any other data type can appear. For example, the following
are legal in Apex:
Pair<String, String> y = x.swap();
DoubleUp<String> z = (DoubleUp<String>) y;

In this example, when the compiler compiles the class StringPair, it must check that the class implements all of the methods
in DoubleUp<String> and in Pair<String, String>. So the compliler substitutes String for T and String for U inside
the body of interface Pair<T, U>.
DoubleUp<String> x = new StringPair('foo', 'bar');

124

Classes, Objects, and Interfaces

Parameterized Typing and Interfaces

This means that the following method prototypes must implement in StringPair for the class to successfully compile:
String getFirst();
String getSecond();
void setFirst(String val);
void setSecond(String val);
Pair<String, String> swap();

Overloading Methods
In this example, the following interface is used:
public interface Overloaded<T> {
void foo(T x);
void foo(String x);
}

The interface Overloaded is legal in Apex: you can overload a method by defining two or more methods with the same name
but different parameters. However, you cannot have any ambiguity when invoking an overloaded method.
The following class successfully implements the Overloaded interface because it simultaneously implements both method
prototypes specified in the interface:
public class MyClass implements Overloaded<String> {
public void foo(String x) {}
}

The following executes successfully because m is typed as MyClass, therefore MyClass.foo is the unique, matching method.
MyClass m = new MyClass();
m.foo('bar');

The following does not execute successfully because o is typed as Overloaded<String>, and so there are two matching
methods for o.foo(), neither of which typed to a specific method. The compiler cannot distinguish which of the two matching
methods should be used. :
Overloaded<String> o = m;
o.foo('bar');

Subtyping with Parameterized Lists


In Apex, if type T is a subtype of U, then List<T> would be a subtype of List<U>. For example, the following is legal:
List<String> slst = new List<String> {'foo', 'bar'};
List<Object> olst = slst;

However, you cannot use this in interfaces with parameterized types, such as for List, Map or Set. The following is not legal:
public interface I<T> {}
I<String> x = ...;
I<Object> y = x; // Compile error: Illegal assignment from I<String> to I<Object>

125

Classes, Objects, and Interfaces

Custom Iterators

Custom Iterators
An iterator traverses through every item in a collection. For example, in a while loop in Apex, you define a condition for
exiting the loop, and you must provide some means of traversing the collection, that is, an iterator. In the following example,
count is incremented by 1 every time the loop is executed (count++) :
while (count < 11) {
System.debug(count);
count++;
}

Using the Iterator interface you can create a custom set of instructions for traversing a List through a loop. This is useful
for data that exists in sources outside of Salesforce that you would normally define the scope of using a SELECT statement.
Iterators can also be used if you have multiple SELECT statements.

Using Custom Iterators


To use custom iterators, you must create an Apex class that implements the Iterator interface.
The Iterator interface has the following instance methods:
Name

Arguments

Returns

Description

hasNext

Boolean

Returns true if there is another item in the collection


being traversed, false otherwise.

next

Any type

Returns the next item in the collection.

All methods in the Iterator interface must be declared as global.


You can only use a custom iterator in a while loop. For example:
IterableString x = new IterableString('This is a really cool test.');
while(x.hasNext()){
system.debug(x.next());
}

Iterators are not currently supported in for loops.

Using Custom Iterators with Iterable


If you do not want to use a custom iterator with a list, but instead want to create your own data structure, you can use the
Iterable interface to generate the data structure.
The Iterable interface has the following method:
Name
iterator

Arguments

Returns

Description

Iterator class

Returns a reference to the iterator for this interface.

The iterator method must be declared as global. It creates a reference to the iterator that you can then use to traverse
the data structure.

126

Classes, Objects, and Interfaces

Custom Iterators

In the following example a custom iterator iterates through a collection:


global class CustomIterable
implements Iterator<Account>{
List<Account> accs {get; set;}
Integer i {get; set;}
public CustomIterable(){
accs =
[SELECT Id, Name,
NumberOfEmployees
FROM Account
WHERE Name = 'false'];
i = 0;
}
global boolean hasNext(){
if(i >= accs.size()) {
return false;
} else {
return true;
}
}
global Account next(){
// 8 is an arbitrary
// constant in this example
// that represents the
// maximum size of the list.
if(i == 8){return null;}
i++;
return accs[i-1];
}
}

The following calls the above code:


global class foo implements iterable<Account>{
global Iterator<Account> Iterator(){
return new CustomIterable();
}
}

The following is a batch job that uses an iterator:


global class batchClass implements Database.batchable<Account>{
global Iterable<Account> start(Database.batchableContext info){
return new foo();
}
global void execute(Database.batchableContext info, List<Account> scope){
List<Account> accsToUpdate = new List<Account>();
for(Account a : scope){
a.Name = 'true';
a.NumberOfEmployees = 69;
accsToUpdate.add(a);
}
update accsToUpdate;
}
global void finish(Database.batchableContext info){
}
}

127

Classes, Objects, and Interfaces

Keywords

Keywords
Apex has the following keywords available:

final
instanceof
super
this
transient
with sharing and without sharing

Using the final Keyword


You can use the final keyword to modify variables.

Final variables can only be assigned a value once, either when you declare a variable or in initialization code. You must
assign a value to it in one of these two places.
Static final variables can be changed in static initialization code or where defined.
Member final variables can be changed in initialization code blocks, constructors, or with other variable declarations.
To define a constant, mark a variable as both static and final (see Constants on page 55).
Non-final static variables are used to communicate state at the class level (such as state between triggers). However, they
are not shared across requests.
Methods and classes are final by default. You cannot use the final keyword in the declaration of a class or method. This
means they cannot be overridden. Use the virtual keyword if you need to override a method or class.

Using the instanceof Keyword


If you need to verify at runtime whether an object is actually an instance of a particular class, use the instanceof keyword.
The instanceof keyword can only be used to verify if the target type in the expression on the right of the keyword is a viable
alternative for the declared type of the expression on the left.
You could add the following check to the Report class in the classes and casting example before you cast the item back into
a CustomReport object.
If (Reports.get(0) instanceof CustomReport) {
// Can safely cast it back to a custom report object
CustomReport c = (CustomReport) Reports.get(0);
} Else {
// Do something with the non-custom-report.
}

Using the super Keyword


The super keyword can be used by classes that are extended from virtual or abstract classes. By using super, you can override
constructors and methods from the parent class.

128

Classes, Objects, and Interfaces

Using the super Keyword

For example, if you have the following virtual class:


public virtual class SuperClass {
public String mySalutation;
public String myFirstName;
public String myLastName;
public SuperClass() {
mySalutation = 'Mr.';
myFirstName = 'Carl';
myLastName = 'Vonderburg';
}
public SuperClass(String salutation, String firstName, String lastName) {
mySalutation = salutation;
myFirstName = firstName;
myLastName = lastName;
}
public virtual void printName() {
System.debug('My name is ' + mySalutation + myLastName);
}
public virtual String getFirstName() {
return myFirstName;
}
}

You can create the following class that extends Superclass and overrides its printName method:
public class Subclass extends Superclass {
public override void printName() {
super.printName();
System.debug('But you can call me ' + super.getFirstName());
}
}

The expected output when calling Subclass.printName is My name is Mr. Vonderburg. But you can call
me Carl.
You can also use super to call constructors. Add the following constructor to SubClass:
public Subclass() {
super('Madam', 'Brenda', 'Clapentrap');
}

Now, the expected output of Subclass.printName is My name is Madam Clapentrap. But you can call
me Brenda.

Best Practices for Using the super Keyword

Only classes that are extending from virtual or abstract classes can use super.
You can only use super in methods that are designated with the override keyword.

129

Classes, Objects, and Interfaces

Using the this Keyword

Using the this Keyword


There are two different ways of using the this keyword.
You can use the this keyword in dot notation, without parenthesis, to represent the current instance of the class in which it
appears. Use this form of the this keyword to access instance variables and methods. For example:
public class myTestThis {
string s;
{
this.s = 'TestString';
}
}

In the above example, the class myTestThis declares an instance variable s. The initialization code populates the variable
using the this keyword.
Or you can use the this keyword to do constructor chaining, that is, in one constructor, call another constructor. In this
format, use the this keyword with parentheses. For example:
public class testThis {
// First constructor for the class. It requires a string parameter.
public testThis(string s2) {
}
// Second constructor for the class. It does not require a parameter.
// This constructor calls the first constructor using the this keyword.
public testThis() {
this('None');
}
}

When you use the this keyword in a constructor to do constructor chaining, it must be the first statement in the constructor.

Using the transient Keyword


Use the transient keyword to declare instance variables that can't be saved, and shouldn't be transmitted as part of the view
state for a Visualforce page. For example:
Transient Integer currentTotal;

You can also use the transient keyword in Apex classes that are serializable, namely in controllers, controller extensions,
or classes that implement the Batchable or Schedulable interface. In addition, you can use transient in classes that
define the types of fields declared in the serializable classes.
Declaring variables as transient reduces view state size. A common use case for the transient keyword is a field on a
Visualforce page that is needed only for the duration of a page request, but should not be part of the page's view state and
would use too many system resources to be recomputed many times during a request.
Some Apex objects are automatically considered transient, that is, their value does not get saved as part of the page's view
state. These objects include the following:

PageReferences

130

Classes, Objects, and Interfaces

Using the with sharing or without sharing Keywords

XmlStream classes
Collections automatically marked as transient only if the type of object that they hold is automatically marked as transient,
such as a collection of Savepoints
Most of the objects generated by system methods, such as Schema.getGlobalDescribe.
JSONParser class instances. For more information, see JSON Support on page 370.

Static variables also don't get transmitted through the view state.
The following example contains both a Visualforce page and a custom controller. Clicking the refresh button on the page
causes the transient date to be updated because it is being recreated each time the page is refreshed. The non-transient date
continues to have its original value, which has been deserialized from the view state, so it remains the same.
<apex:page controller="ExampleController">
T1: {!t1} <br/>
T2: {!t2} <br/>
<apex:form>
<apex:commandLink value="refresh"/>
</apex:form>
</apex:page>
public class ExampleController {
DateTime t1;
transient DateTime t2;
public String getT1() {
if (t1 == null) t1 = System.now();
return '' + t1;
}
public String getT2() {
if (t2 == null) t2 = System.now();
return '' + t2;
}
}

Using the with sharing or without sharing Keywords


Apex generally runs in system context; that is, the current user's permissions, field-level security, and sharing rules arent taken
into account during code execution.
Note: The only exceptions to this rule are Apex code that is executed with the executeAnonymous call.
executeAnonymous always executes using the full permissions of the current user. For more information on
executeAnonymous, see Anonymous Blocks on page 103.
Because these rules aren't enforced, developers who use Apex must take care that they don't inadvertently expose sensitive
data that would normally be hidden from users by user permissions, field-level security, or organization-wide defaults. They
should be particularly careful with Web services, which can be restricted by permissions, but execute in system context once
they are initiated.
Most of the time, system context provides the correct behavior for system-level operations such as triggers and Web services
that need access to all data in an organization. However, you can also specify that particular Apex classes should enforce the
sharing rules that apply to the current user. (For more information on sharing rules, see the Salesforce.com online help.)

131

Classes, Objects, and Interfaces

Using the with sharing or without sharing Keywords

Note: A user's permissions and field-level security are always ignored to ensure that Apex code can view all fields and
objects in an organization. If particular fields or objects are hidden for a user, the code would fail to compile at runtime.
Use the with sharing keywords when declaring a class to enforce the sharing rules that apply to the current user. For
example:
public with sharing class sharingClass {
// Code here
}

Use the without sharing keywords when declaring a class to ensure that the sharing rules for the current user are not
enforced. For example:
public without sharing class noSharing {
// Code here
}

If a class is not declared as either with or without sharing, the current sharing rules remain in effect. This means that if the
class is called by a class that has sharing enforced, then sharing is enforced for the called class.
Both inner classes and outer classes can be declared as with sharing. The sharing setting applies to all code contained in
the class, including initialization code, constructors, and methods. Classes inherit this setting from a parent class when one
class extends or implements another, but inner classes do not inherit the sharing setting from their container class.
For example:
public with sharing class CWith {
// All code in this class operates with enforced sharing rules.
Account a = [SELECT . . . ];
public static void m() { . . . }
static {
. . .
}
{
. . .
}
public c() {
. . .
}
}
public without sharing class CWithout {
// All code in this class ignores sharing rules and operates
// as if the context user has the Modify All Data permission.
Account a = [SELECT . . . ];
. . .
public static void m() {
. . .
// This call into CWith operates with enforced sharing rules

132

Classes, Objects, and Interfaces

Annotations

// for the context user. When the call finishes, the code execution
// returns to without sharing mode.
CWith.m();
}
public class CInner {
// All code in this class executes with the same sharing context
// as the code that calls it.
// Inner classes are separate from outer classes.
. . .
// Again, this call into CWith operates with enforced sharing rules
// for the context user, regardless of the class that initially called this inner class.
// When the call finishes, the code execution returns to the sharing mode that was used
to call this inner class.
CWith.m();
}
public class CInnerWithOut exends CWithout {
// All code in this class ignores sharing rules because
// this class extends a parent class that ignores sharing rules.
}
}

Caution: There is no guarantee that a class declared as with sharing doesn't call code that operates as without
sharing. Class-level security is always still necessary. In addition, all SOQL or SOSL queries that use PriceBook2
ignore the with sharing keyword. All PriceBook records are returned, regardless of the applied sharing rules.
Enforcing the current user's sharing rules can impact:

SOQL and SOSL queries. A query may return fewer rows than it would operating in system context.
DML operations. An operation may fail because the current user doesn't have the correct permissions. For example, if the
user specifies a foreign key value that exists in the organization, but which the current user does not have access to.

Annotations
An Apex annotation modifies the way a method or class is used, similar to annotations in Java.
Annotations are defined with an initial @ symbol, followed by the appropriate keyword. To add an annotation to a method,
specify it immediately before the method or class definition. For example:

global class MyClass {


@future
Public static void myMethod(String a)
{
//long-running Apex code
}
}

Apex supports the following annotations:

@Deprecated
@Future

133

Classes, Objects, and Interfaces

Deprecated Annotation

@IsTest
@ReadOnly
@RemoteAction

Apex REST annotations:

@RestResource(urlMapping='/yourUrl')
@HttpDelete
@HttpGet
@HttpPatch
@HttpPost
@HttpPut

Deprecated Annotation
Use the deprecated annotation to identify methods, classes, exceptions, enums, interfaces, or variables that can no longer
be referenced in subsequent releases of the managed package in which they reside. This is useful when you are refactoring
code in managed packages as the requirements evolve. New subscribers cannot see the deprecated elements, while the elements
continue to function for existing subscribers and API integrations.
The following code snippet shows a deprecated method. The same syntax can be used to deprecate classes, exceptions, enums,
interfaces, or variables.
@deprecated
// This method is deprecated. Use myOptimizedMethod(String a, String b) instead.
public void myMethod(String a) {
}

Note the following rules when deprecating Apex identifiers:

Unmanaged packages cannot contain code that uses the deprecated keyword.
When something in Apex, or when a custom object is deprecated, all global access modifiers that reference the deprecated
identifier must also be deprecated. Any global method that uses the deprecated type in its signature, either in an input
argument or the method return type, must also be deprecated. A deprecated item, such as a method or a class, can still be
referenced internally by the package developer.
webService methods and variables cannot be deprecated.
You can deprecate an enum but you cannot deprecate individual enum values.
You can deprecate an interface but you cannot deprecate individual methods in an interface.
You can deprecate an abstract class but you cannot deprecate individual abstract methods in an abstract class.
You cannot remove the deprecated annotation to undeprecate something in Apex after you have released a package
version where that item in Apex is deprecated.

For more information about package versions, see Developing Apex in Managed Packages on page 228.

Future Annotation
Use the future annotation to identify methods that are executed asynchronously. When you specify future, the method
executes when Salesforce has available resources.

134

Classes, Objects, and Interfaces

Future Annotation

For example, you can use the future annotation when making an asynchronous Web service callout to an external service.
Without the annotation, the Web service callout is made from the same thread that is executing the Apex code, and no
additional processing can occur until the callout is complete (synchronous processing).
Methods with the future annotation must be static methods, and can only return a void type.
To make a method in a class execute asynchronously, define the method with the future annotation. For example:
global class MyFutureClass {
@future
static void myMethod(String a, Integer i) {
System.debug('Method called with: ' + a + ' and ' + i);
//do callout, other long running code
}
}

The following snippet shows how to specify that a method executes a callout:
@future (callout=true)
public static void doCalloutFromFuture() {
//Add code to perform callout
}

You can specify (callout=false) to prevent a method from making callouts.


To test methods defined with the future annotation, call the class containing the method in a startTest, stopTest code
block. All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed,
all asynchronous processes are run synchronously.
Methods with the future annotation have the following limits:

No more than 10 method calls per Apex invocation


Note: Asynchronous calls, such as @future or executeBatch, called in a startTest, stopTest block, do
not count against your limits for the number of queued jobs.

Salesforce also imposes a limit on the number of future method invocations: 200 method calls per full Salesforce user
license, Salesforce Platform user license, or Force.com - One App user license, per 24 hours. This is an organization-wide
limit. Chatter Only, Chatter customer users, Customer Portal User, and partner portal User licenses arent included in this
limit calculation. For example, suppose your organization has three full Salesforce licenses, two Salesforce Platform licenses,
and 100 Customer Portal User licenses. Your entire organization is limited to only 1,000 method calls every 24 hours
((3+2) * 200, not 105.)
The parameters specified must be primitive dataypes, arrays of primitive datatypes, or collections of primitive datatypes.
Methods with the future annotation cannot take sObjects or objects as arguments.
Methods with the future annotation cannot be used in Visualforce controllers in either getMethodName or
setMethodName methods, nor in the constructor.

Remember that any method using the future annotation requires special consideration, because the method does not
necessarily execute in the same order it is called.
You cannot call a method annotated with future from a method that also has the future annotation. Nor can you call a
trigger from an annotated method that calls another annotated method.
The getContent and getContentAsPDF PageReference methods cannot be used in methods with the future annotation.

135

Classes, Objects, and Interfaces

IsTest Annotation

For more information about callouts, see Invoking Callouts Using Apex on page 248.

See Also:
Understanding Execution Governors and Limits

IsTest Annotation
Use the isTest annotation to define classes or individual methods that only contain code used for testing your application.
The isTest annotation is similar to creating methods declared as testMethod.
Note: Classes defined with the isTest annotation don't count against your organization limit of 2 MB for all Apex
code. Individual methods defined with the isTest annotation do count against your organization limits. See
Understanding Execution Governors and Limits on page 222.
Starting with Apex code saved using Salesforce.com API version 24.0, test methods dont have access by default to pre-existing
data in the organization. However, test code saved against Salesforce.com API version 23.0 or earlier continues to have access
to all data in the organization and its data access is unchanged. See Isolation of Test Data from Organization Data in Unit
Tests on page 157.
Classes and methods defined as isTest can be either private or public. Classes defined as isTest must be top-level
classes.
This is an example of a private test class that contains two test methods.
@isTest
private class MyTestClass {
// Methods for testing
@isTest static void test1() {
// Implement test code
}
@isTest static void test2() {
// Implement test code
}
}

This is an example of a public test class that contains utility methods for test data creation:
@isTest
public class TestUtil {
public static void createTestAccounts() {
// Create some test accounts
}
public static void createTestContacts() {
// Create some test contacts
}
}

Classes defined as isTest can't be interfaces or enums.

136

Classes, Objects, and Interfaces

IsTest Annotation

Methods of a public test class can only be called from a running test, that is, a test method or code invoked by a test method,
and can't be called by a non-test request. In addition, test class methods can be invoked using the Salesforce user interface or
the API. For more information, see Running Unit Test Methods.

IsTest(SeeAllData=true) Annotation
For Apex code saved using Salesforce.com API version 24.0 and later, use the isTest(SeeAllData=true) annotation to
grant test classes and individual test methods access to all data in the organization, including pre-existing data that the test
didnt create. Starting with Apex code saved using Salesforce.com API version 24.0, test methods dont have access by default
to pre-existing data in the organization. However, test code saved against Salesforce.com API version 23.0 or earlier continues
to have access to all data in the organization and its data access is unchanged. See Isolation of Test Data from Organization
Data in Unit Tests on page 157.
Considerations of the IsTest(SeeAllData=true) Annotation
If a test class is defined with the isTest(SeeAllData=true) annotation, this annotation applies to all its test
methods whether the test methods are defined with the @isTest annotation or the testmethod keyword.
The isTest(SeeAllData=true) annotation is used to open up data access when applied at the class or method
level. However, using isTest(SeeAllData=false) on a method doesnt restrict organization data access for that
method if the containing class has already been defined with the isTest(SeeAllData=true) annotation. In this
case, the method will still have access to all the data in the organization.

This example shows how to define a test class with the isTest(SeeAllData=true) annotation. All the test methods in
this class have access to all data in the organization.
// All test methods in this class can access all data.
@isTest(SeeAllData=true)
public class TestDataAccessClass {
// This test accesses an existing account.
// It also creates and accesses a new test account.
static testmethod void myTestMethod1() {
// Query an existing account in the organization.
Account a = [SELECT Id, Name FROM Account WHERE Name='Acme' LIMIT 1];
System.assert(a != null);
// Create a test account based on the queried account.
Account testAccount = a.clone();
testAccount.Name = 'Acme Test';
insert testAccount;
// Query the test account that was inserted.
Account testAccount2 = [SELECT Id, Name FROM Account
WHERE Name='Acme Test' LIMIT 1];
System.assert(testAccount2 != null);
}
// Like the previous method, this test method can also access all data
// because the containing class is annotated with @isTest(SeeAllData=true).
@isTest static void myTestMethod2() {
// Can access all data in the organization.
}
}

This second example shows how to apply the isTest(SeeAllData=true) annotation on a test method. Because the class
that the test method is contained in isnt defined with this annotation, you have to apply this annotation on the test method

137

Classes, Objects, and Interfaces

IsTest Annotation

to enable access to all data for that test method. The second test method doesnt have this annotation, so it can access only
the data it creates in addition to objects that are used to manage your organization, such as users.
// This class contains test methods with different data access levels.
@isTest
private class ClassWithDifferentDataAccess {
// Test method that has access to all data.
@isTest(SeeAllData=true)
static void testWithAllDataAccess() {
// Can query all data in the organization.
}
// Test method that has access to only the data it creates
// and organization setup and metadata objects.
@isTest static void testWithOwnDataAccess() {
// This method can still access the User object.
// This query returns the first user object.
User u = [SELECT UserName,Email FROM User LIMIT 1];
System.debug('UserName: ' + u.UserName);
System.debug('Email: ' + u.Email);
// Can access the test account that is created here.
Account a = new Account(Name='Test Account');
insert a;
// Access the account that was just created.
Account insertedAcct = [SELECT Id,Name FROM Account
WHERE Name='Test Account'];
System.assert(insertedAcct != null);
}
}

IsTest(OnInstall=true) Annotation
Use the IsTest(OnInstall=true) annotation to specify which Apex tests are executed during package installation. This
annotation is used for tests in managed or unmanaged packages. Only test methods with this annotation, or methods that are
part of a test class that has this annotation, will be executed during package installation. Tests annotated to run during package
installation must pass in order for the package installation to succeed. It is no longer possible to bypass a failing test during
package installation. A test method or a class that doesn't have this annotation, or that is annotated with
isTest(OnInstall=false) or isTest, won't be executed during installation.
This example shows how to annotate a test method that will be executed during package installation. In this example, test1
will be executed but test2 and test3 won't.
public class OnInstallClass {
// Implement logic for the class.
public void method1(){
// Some code
}
// This test method will be executed
// during the installation of the package.
@isTest(OnInstall=true)
static void test1() {
// Some test code
}
// Tests excluded from running during the
// the installation of a package.
@isTest
static void test2() {
// Some test code

138

Classes, Objects, and Interfaces

ReadOnly Annotation

}
static testmethod void test3() {
// Some test code
}
}

ReadOnly Annotation
The @ReadOnly annotation allows you to perform unrestricted queries against the Force.com database. All other limits still
apply. It's important to note that this annotation, while removing the limit of the number of returned rows for a request, blocks
you from performing the following operations within the request: DML operations, calls to System.schedule, calls to
methods annotated with @future, and sending emails.
The @ReadOnly annotation is available for Web services and the Schedulable interface. To use the @ReadOnly annotation,
the top level request must be in the schedule execution or the Web service invocation. For example, if a Visualforce page calls
a Web service that contains the @ReadOnly annotation, the request fails because Visualforce is the top level request, not the
Web service.
Visualforce pages can call controller methods with the @ReadOnly annotation, and those methods will run with the same
relaxed restrictions. To increase other Visualforce-specific limits, such as the size of a collection that can be used by an iteration
component like <apex:pageBlockTable>, you can set the readonly attribute on the <apex:page> tag to true. For
more information, see Working with Large Sets of Data in the Visualforce Developer's Guide.

RemoteAction Annotation
The RemoteAction annotation provides support for Apex methods used in Visualforce to be called via Javascript. This
process is often referred to as Javascript remoting.
Note: Methods with the RemoteAction annotation must be static and either global or public.

To use JavaScript remoting in a Visualforce page, you add the request as a JavaScript invocation, which has the following form:
[namespace.]controller.method(
[parameters...,]
callbackFunction,
[configuration]
);

where

namespace is the namespace of the controller class. This is required if your organization has a namespace defined, or if

the class comes from an installed package.


controller is the name of your Apex controller.
method is the name of the Apex method youre calling.
parameters is the comma-separated list of parameters that your method takes.
callbackFunction is the name of the JavaScript function that will handle the response from the controller. You can
also declare an anonymous function inline. callbackFunction receives the status of the method call and the result as
parameters.

139

Classes, Objects, and Interfaces

Apex REST Annotations

configuration configures the handling of the remote call and response. Use this to specify whether your Apex methods
response should be escaped. If omitted, this defaults to {escape: true}.

In your controller, your Apex method declaration is preceded with the @RemoteAction annotation like this:
@RemoteAction
global static String getItemId(String objectName) { ... }

Your method can take Apex primitives, collections, typed and generic sObjects, and user-defined Apex classes and interfaces
as arguments. Generic sObjects must have an ID or sobjectType value to identify actual type. Interface parameters must have
an apexType to identify actual type. Your method can return Apex primitives, sObjects, collections, user-defined Apex classes
and enums, SaveResult, UpsertResult, DeleteResult, SelectOption, or PageReference.
For more information, see JavaScript Remoting for Apex Controllers in the Visualforce Developer's Guide.

Apex REST Annotations


Six new annotations have been added that enable you to expose an Apex class as a RESTful Web service.

@RestResource(urlMapping='/yourUrl')
@HttpDelete
@HttpGet
@HttpPatch
@HttpPost
@HttpPut

See Also:
Apex REST Basic Code Sample
RestResource Annotation

The @RestResource annotation is used at the class level and enables you to expose an Apex class as a REST resource.
These are some considerations when using this annotation:

The URL mapping is relative to https://instance.salesforce.com/services/apexrest/.


A wildcard character (*) may be used.
To use this annotation, your Apex class must be defined as global.

URL Guidelines
URL path mappings are as follows:

The path must begin with a '/'


If an '*' appears, it must be preceded by '/' and followed by '/', unless the '*' is the last character, in which case it need not
be followed by '/'

The rules for mapping URLs are:

An exact match always wins.

140

Classes, Objects, and Interfaces

Apex REST Annotations

If no exact match is found, find all the patterns with wildcards that match, and then select the longest (by string length)
of those.
If no wildcard match is found, an HTTP response status code 404 is returned.

The URL for a namespaced classes contains the namespace. For example, if your class is in namespace abc and the class is
mapped to your_url, then the API URL is modified as follows:
https://instance.salesforce.com/services/apexrest/abc/your_url/. In the case of a URL collision, the
namespaced class is always used.
HttpDelete Annotation

The @HttpDelete annotation is used at the method level and enables you to expose an Apex method as a REST resource.
This method is called when an HTTP DELETE request is sent, and deletes the specified resource.
To use this annotation, your Apex method must be defined as global static.
HttpGet Annotation

The @HttpGet annotation is used at the method level and enables you to expose an Apex method as a REST resource. This
method is called when an HTTP GET request is sent, and returns the specified resource.
These are some considerations when using this annotation:

To use this annotation, your Apex method must be defined as global static.
Methods annotated with @HttpGet are also called if the HTTP request uses the HEAD request method.

HttpPatch Annotation

The @HttpPatch annotation is used at the method level and enables you to expose an Apex method as a REST resource.
This method is called when an HTTP PATCH request is sent, and updates the specified resource.
To use this annotation, your Apex method must be defined as global static.
HttpPost Annotation

The @HttpPost annotation is used at the method level and enables you to expose an Apex method as a REST resource. This
method is called when an HTTP POST request is sent, and creates a new resource.
To use this annotation, your Apex method must be defined as global static.
HttpPut Annotation

The @HttpPut annotation is used at the method level and enables you to expose an Apex method as a REST resource. This
method is called when an HTTP PUT request is sent, and creates or updates the specified resource.
To use this annotation, your Apex method must be defined as global static.

141

Classes, Objects, and Interfaces

Classes and Casting

Classes and Casting


In general, all type information is available at runtime. This means that Apex enables casting, that is, a data type of one class
can be assigned to a data type of another class, but only if one class is a child of the other class. Use casting when you want to
convert an object from one data type to another.
In the following example, CustomReport extends the class Report. Therefore, it is a child of that class. This means that
you can use casting to assign objects with the parent data type (Report) to the objects of the child data type (CustomReport).
In the following code block, first, a custom report object is added to a list of report objects. After that, the custom report object
is returned as a report object, then is cast back into a custom report object.
Public virtual class Report {
Public class CustomReport extends Report {
// Create a list of report objects
Report[] Reports = new Report[5];
// Create a custom report object
CustomReport a = new CustomReport();
// Because the custom report is a sub class of the Report class,
// you can add the custom report object a to the list of report objects
Reports.add(a);
//
//
//
//

The following is not legal, because the compiler does not know that what you are
returning is a custom report. You must use cast to tell it that you know what
type you are returning
CustomReport c = Reports.get(0);

// Instead, get the first item in the list by casting it back to a custom report object
CustomReport c = (CustomReport) Reports.get(0);
}
}

142

Classes, Objects, and Interfaces

Classes and Collections

Figure 4: Casting Example


In addition, an interface type can be cast to a sub-interface or a class type that implements that interface.
Tip: To verify if a class is a specific type of class, use the instanceOf keyword. For more information, see Using
the instanceof Keyword on page 128.

Classes and Collections


Lists and maps can be used with classes and interfaces, in the same ways that lists and maps can be used with sObjects. This
means, for example, that you can use a user-defined data type only for the value of a map, not for the key. Likewise, you cannot
create a set of user-defined objects.
If you create a map or list of interfaces, any child type of the interface can be put into that collection. For instance, if the List
contains an interface i1, and MyC implements i1, then MyC can be placed in the list.

Collection Casting
Because collections in Apex have a declared type at runtime, Apex allows collection casting.

143

Classes, Objects, and Interfaces

Differences Between Apex Classes and Java Classes

Collections can be cast in a similar manner that arrays can be cast in Java. For example, a list of CustomerPurchaseOrder
objects can be assigned to a list of PurchaseOrder objects if class CustomerPurchaseOrder is a child of class PurchaseOrder.
public virtual class PurchaseOrder {
Public class CustomerPurchaseOrder extends PurchaseOrder {
}
{
List<PurchaseOrder> POs = new PurchaseOrder[] {};
List<CustomerPurchaseOrder> CPOs = new CustomerPurchaseOrder[]{};
POs = CPOs;}
}

Once the CustomerPurchaseOrder list is assigned to the PurchaseOrder list variable, it can be cast back to a list of
CustomerPurchaseOrder objects, but only because that instance was originally instantiated as a list of CustomerPurchaseOrder.
A list of PurchaseOrder objects that is instantiated as such cannot be cast to a list of CustomerPurchaseOrder objects, even if
the list of PurchaseOrder objects contains only CustomerPurchaseOrder objects.
If the user of a PurchaseOrder list that only includes CustomerPurchaseOrders objects tries to insert a
non-CustomerPurchaseOrder subclass of PurchaseOrder (such as InternalPurchaseOrder), a runtime exception results.
This is because Apex collections have a declared type at runtime.
Note: Maps behave in the same way as lists with regards to the value side of the Mapif the value side of map A can
be cast to the value side of map B, and they have the same key type, then map A can be cast to map B. A runtime error
results if the casting is not valid with the particular map at runtime.

Differences Between Apex Classes and Java Classes


The following is a list of the major differences between Apex classes and Java classes:

Inner classes and interfaces can only be declared one level deep inside an outer class.
Static methods and variables can only be declared in a top-level class definition, not in an inner class.
Inner classes behave like static Java inner classes, but do not require the static keyword. Inner classes can have instance
member variables like outer classes, but there is no implicit pointer to an instance of the outer class (using the this
keyword).
The private access modifier is the default, and means that the method or variable is accessible only within the Apex
class in which it is defined. If you do not specify an access modifier, the method or variable is private.
Specifying no access modifier for a method or variable and the private access modifier are synonymous.
The public access modifier means the method or variable can be used by any Apex in this application or namespace.
The global access modifier means the method or variable can be used by any Apex code that has access to the class, not
just the Apex code in the same application. This access modifier should be used for any method that needs to be referenced
outside of the application, either in the SOAP API or by other Apex code. If you declare a method or variable as global,
you must also declare the class that contains it as global.
Methods and classes are final by default.
The virtual definition modifier allows extension and overrides.
The override keyword must be used explicitly on methods that override base class methods.

Interface methods have no modifiersthey are always global.

144

Classes, Objects, and Interfaces

Class Definition Creation

Exception classes must extend either exception or another user-defined exception.


Their names must end with the word exception.
Exception classes have four implicit constructors that are built-in, although you can add others.
For more information, see Exception Class on page 442.

Classes and interfaces can be defined in triggers and anonymous blocks, but only as local.

Class Definition Creation


To create a class in Salesforce:
1. Click Your Name > Setup > Develop > Apex Classes.
2. Click New.
3. Click Version Settings to specify the version of Apex and the API used with this class. If your organization has installed
managed packages from the AppExchange, you can also specify which version of each managed package to use with this
class. Use the default values for all versions. This associates the class with the most recent version of Apex and the API,
as well as each managed package. You can specify an older version of a managed package if you want to access components
or functionality that differs from the most recent package version. You can specify an older version of Apex and the API
to maintain specific behavior.
4. In the class editor, enter the Apex code for the class. A single class can be up to 1 million characters in length, not including
comments, test methods, or classes defined using @isTest.
5. Click Save to save your changes and return to the class detail screen, or click Quick Save to save your changes and continue
editing your class. Your Apex class must compile correctly before you can save your class.
Classes can also be automatically generated from a WSDL by clicking Generate from WSDL. See SOAP Services: Defining
a Class from a WSDL Document on page 249.
Once saved, classes can be invoked through class methods or variables by other Apex code, such as a trigger.
Note: To aid backwards-compatibility, classes are stored with the version settings for a specified version of Apex and
the API. If the Apex class references components, such as a custom object, in installed managed packages, the version
settings for each managed package referenced by the class is saved too. Additionally, classes are stored with an isValid
flag that is set to true as long as dependent metadata has not changed since the class was last compiled. If any changes
are made to object names or fields that are used in the class, including superficial changes such as edits to an object or
field description, or if changes are made to a class that calls this class, the isValid flag is set to false. When a
trigger or Web service call invokes the class, the code is recompiled and the user is notified if there are any errors. If
there are no errors, the isValid flag is reset to true.

The Apex Class Editor


When editing Visualforce or Apex, either in the Visualforce development mode footer or from Setup, an editor is available
with the following functionality:
Syntax highlighting
The editor automatically applies syntax highlighting for keywords and all functions and operators.

145

Classes, Objects, and Interfaces

Naming Conventions

Search ( )
Search enables you to search for text within the current page, class, or trigger. To use search, enter a string in the Search
textbox and click Find Next.

To replace a found search string with another string, enter the new string in the Replace textbox and click replace
to replace just that instance, or Replace All to replace that instance and all other instances of the search string that
occur in the page, class, or trigger.
To make the search operation case sensitive, select the Match Case option.
To use a regular expression as your search string, select the Regular Expressions option. The regular expressions
follow Javascript's regular expression rules. A search using regular expressions can find strings that wrap over more
than one line.
If you use the replace operation with a string found by a regular expression, the replace operation can also bind regular
expression group variables ($1, $2, and so on) from the found search string. For example, to replace an <H1> tag
with an <H2> tag and keep all the attributes on the original <H1> intact, search for <H1(\s+)(.*)> and replace it
with <H2$1$2>.

Go to line ( )
This button allows you to highlight a specified line number. If the line is not currently visible, the editor scrolls to that
line.
Undo ( ) and Redo ( )
Use undo to reverse an editing action and redo to recreate an editing action that was undone.
Font size
Select a font size from the drop-down list to control the size of the characters displayed in the editor.
Line and column position
The line and column position of the cursor is displayed in the status bar at the bottom of the editor. This can be used
with go to line (

) to quickly navigate through the editor.

Line and character count


The total number of lines and characters is displayed in the status bar at the bottom of the editor.

Naming Conventions
We recommend following Java standards for naming, that is, classes start with a capital letter, methods start with a lowercase
verb, and variable names should be meaningful.
It is not legal to define a class and interface with the same name in the same class. It is also not legal for an inner class to have
the same name as its outer class. However, methods and variables have their own namespaces within the class so these three
types of names do not clash with each other. In particular it is legal for a variable, method, and a class within a class to have
the same name.

146

Classes, Objects, and Interfaces

Name Shadowing

Name Shadowing
Member variables can be shadowed by local variablesin particular function arguments. This allows methods and constructors
of the standard Java form:
Public Class Shadow {
String s;
Shadow(String s) { this.s = s; } // Same name ok
setS(String s) { this.s = s; } // Same name ok
}

Member variables in one class can shadow member variables with the same name in a parent classes. This can be useful if the
two classes are in different top-level classes and written by different teams. For example, if one has a reference to a class C and
wants to gain access to a member variable M in parent class P (with the same name as a member variable in C) the reference
should be assigned to a reference to P first.
Static variables can be shadowed across the class hierarchyso if P defines a static S, a subclass C can also declare a static S.
References to S inside C refer to that staticin order to reference the one in P, the syntax P.S must be used.
Static class variables cannot be referenced through a class instance. They must be referenced using the raw variable name by
itself (inside that top-level class file) or prefixed with the class name. For example:
public class p1 {
public static final Integer CLASS_INT = 1;
public class c { };
}
p1.c c = new p1.c();
// This is illegal
// Integer i = c.CLASS_INT;
// This is correct
Integer i = p1.CLASS_INT;

Class Security
You can specify which users can execute methods in a particular top-level class based on their user profile or permission sets.
You can only set security on Apex classes, not on triggers.
To set Apex class security from the class list page:
1. Click Your Name > Setup > Develop > Apex Classes.
2. Next to the name of the class that you want to restrict, click Security.
3. Select the profiles that you want to enable from the Available Profiles list and click Add, or select the profiles that you
want to disable from the Enabled Profiles list and click Remove.
4. Click Save.
To set Apex class security from the class detail page:
1. Click Your Name > Setup > Develop > Apex Classes.
2. Click the name of the class that you want to restrict.
3. Click Security.

147

Classes, Objects, and Interfaces

Enforcing Object and Field Permissions

4. Select the profiles that you want to enable from the Available Profiles list and click Add, or select the profiles that you
want to disable from the Enabled Profiles list and click Remove.
5. Click Save.
To set Apex class security from a permission set:
1.
2.
3.
4.
5.

Click Your Name > Setup > Manage Users > Permission Sets.
Select a permission set.
Click Apex Class Access.
Click Edit.
Select the Apex classes that you want to enable from the Available Apex Classes list and click Add, or select the Apex
classes that you want to disable from the Enabled Apex Classes list and click Remove.
6. Click Save.
To set Apex class security from a profile:
1.
2.
3.
4.

Click Your Name > Setup > Manage Users > Profiles.
Select a profile.
In the Apex Class Access page or related list, click Edit.
Select the Apex classes that you want to enable from the Available Apex Classes list and click Add, or select the Apex
classes that you want to disable from the Enabled Apex Classes list and click Remove.
5. Click Save.

Enforcing Object and Field Permissions


Apex generally runs in system context; that is, the current user's permissions, field-level security, and sharing rules arent taken
into account during code execution. The only exceptions to this rule are Apex code that is executed with the
executeAnonymous call. executeAnonymous always executes using the full permissions of the current user. For more
information on executeAnonymous, see Anonymous Blocks on page 103.
Although Apex doesn't enforce object-level and field-level permissions by default, you can enforce these permissions in your
code by explicitly calling the sObject describe result methods (of Schema.DescribeSObjectResult) and the field describe result
methods (of Schema.DescribeFieldResult) that check the current user's access permission levels. In this way, you can verify if
the current user has the necessary permissions, and only if he or she has sufficient permissions, you can then perform a specific
DML operation or a query.
For example, you can call the isAccessible, isCreateable, or isUpdateable methods of
Schema.DescribeSObjectResult to verify whether the current user has read, create, or update access to an sObject,
respectively. Similarly, Schema.DescribeFieldResult exposes these access control methods that you can call to check
the current user's read, create, or update access for a field. In addition, you can call the isDeletable method provided by
Schema.DescribeSObjectResult to check if the current user has permission to delete a specific sObject.
These are some examples of how to call the access control methods.
To check the field-level update permission of the contact's email field before updating it:
if (Schema.sObjectType.Contact.fields.Email.isUpdateable()) {
// Update contact phone number
}

148

Classes, Objects, and Interfaces

Namespace Prefix

To check the field-level create permission of the contact's email field before creating a new contact:
if (Schema.sObjectType.Contact.fields.Email.isCreateable()) {
// Create new contact
}

To check the field-level read permission of the contact's email field before querying for this field:
if (Schema.sObjectType.Contact.fields.Email.isAccessible()) {
Contact c = [SELECT Email FROM Contact WHERE Id= :Id];
}

To check the object-level permission for the contact before deleting the contact.
if (Schema.sObjectType.Contact.isDeletable()) {
// Delete contact
}

Sharing rules are distinct from object-level and field-level permissions. They can coexist. If sharing rules are defined in
Salesforce, you can enforce them at the class level by declaring the class with the with sharing keyword. For more information,
see Using the with sharing or without sharing Keywords. If you call the sObject describe result and field describe
result access control methods, the verification of object and field-level permissions is performed in addition to the sharing
rules that are in effect. Sometimes, the access level granted by a sharing rule could conflict with an object-level or field-level
permission.

Namespace Prefix
The application supports the use of namespace prefixes. Namespace prefixes are used in managed Force.com AppExchange
packages to differentiate custom object and field names from those in use by other organizations. After a developer registers
a globally unique namespace prefix and registers it with AppExchange registry, external references to custom object and field
names in the developer's managed packages take on the following long format:
namespace_prefix__obj_or_field_name__c

Because these fully-qualified names can be onerous to update in working SOQL statements, SOSL statements, and Apex
once a class is marked as managed, Apex supports a default namespace for schema names. When looking at identifiers, the
parser considers the namespace of the current object and then assumes that it is the namespace of all other objects and fields
unless otherwise specified. Consequently, a stored class should refer to custom object and field names directly (using
obj_or_field_name__c) for those objects that are defined within its same application namespace.
Tip: Only use namespace prefixes when referring to custom objects and fields in managed packages that have been
installed to your organization from theAppExchange.

Using Namespaces When Invoking Methods


To invoke a method that is defined in a managed package, Apex allows fully-qualified identifiers of the form:
namespace_prefix.class.method(args)

149

Classes, Objects, and Interfaces

Namespace, Class, and Variable Name Precedence

Use the special namespace System to disambiguate the built-in static classes from any user-defined ones (for example,
System.System.debug()).
Without the System namespace prefix, system static class names such as Math and System can be overridden by user-defined
classes with the same name, as outlined below.
Tip: Only use namespace prefixes when invoking methods in managed packages that have been installed to your
organization from theAppExchange.

Namespace, Class, and Variable Name Precedence


Because local variables, class names, and namespaces can all hypothetically use the same identifiers, the Apex parser evaluates
expressions in the form of name1.name2.[...].nameN as follows:
1. The parser first assumes that name1 is a local variable with name2 - nameN as field references.
2. If the first assumption does not hold true, the parser then assumes that name1 is a class name and name2 is a static variable
name with name3 - nameN as field references.
3. If the second assumption does not hold true, the parser then assumes that name1 is a namespace name, name2 is a class
name, name3 is a static variable name, and name4 - nameN are field references.
4. If the third assumption does not hold true, the parser reports an error.
If the expression ends with a set of parentheses (for example, name1.name2.[...].nameM.nameN()), the Apex parser
evaluates the expression as follows:
1. The parser first assumes that name1 is a local variable with name2 - nameM as field references, and nameN as a method
invocation.
2. If the first assumption does not hold true:

If the expression contains only two identifiers (name1.name2()), the parser then assumes that name1 is a class name
and name2 is a method invocation.
If the expression contains more than two identifiers, the parser then assumes that name1 is a class name, name2 is a
static variable name with name3 - nameM as field references, and nameN is a method invocation.

3. If the second assumption does not hold true, the parser then assumes that name1 is a namespace name, name2 is a class
name, name3 is a static variable name, name4 - nameM are field references, and nameN is a method invocation.
4. If the third assumption does not hold true, the parser reports an error.
However, with class variables Apex also uses dot notation to reference member variables. Those member variables might refer
to other class instances, or they might refer to an sObject which has its own dot notation rules to refer to field names (possibly
navigating foreign keys).
Once you enter an sObject field in the expression, the remainder of the expression stays within the sObject domain, that is,
sObject fields cannot refer back to Apex expressions.
For instance, if you have the following class:
public class c {
c1 c1 = new c1();
class c1 { c2 c2; }
class c2 { Account a; }
}

150

Classes, Objects, and Interfaces

Type Resolution and System Namespace for Types

Then the following expressions are all legal:


c.c1.c2.a.name
c.c1.c2.a.owner.lastName.toLowerCase()
c.c1.c2.a.tasks
c.c1.c2.a.contacts.size()

Type Resolution and System Namespace for Types


Because the type system must resolve user-defined types defined locally or in other classes, the Apex parser evaluates types as
follows:
1.
2.
3.
4.

For a type reference TypeN, the parser first looks up that type as a scalar type.
If TypeN is not found, the parser looks up locally defined types.
If TypeN still is not found, the parser looks up a class of that name.
If TypeN still is not found, the parser looks up system types such as sObjects.

For the type T1.T2 this could mean an inner type T2 in a top-level class T1, or it could mean a top-level class T2 in the
namespace T1 (in that order of precedence).

Version Settings
To aid backwards-compatibility, classes and triggers are stored with the version settings for a specific Salesforce.com API
version. If an Apex class or trigger references components, such as a custom object, in installed managed packages, the version
settings for each managed package referenced by the class are saved too. This ensures that as Apex, the API, and the components
in managed packages evolve in subsequent released versions, a class or trigger is still bound to versions with specific, known
behavior.
Setting a version for an installed package determines the exposed interface and behavior of any Apex code in the installed
package. This allows you to continue to reference Apex that may be deprecated in the latest version of an installed package,
if you installed a version of the package before the code was deprecated.
Typically, you reference the latest Salesforce.com API version and each installed package version. If you save an Apex class or
trigger without specifying the Salesforce.com API version, the class or trigger is associated with the latest installed version by
default. If you save an Apex class or trigger that references a managed package without specifying a version of the managed
package, the class or trigger is associated with the latest installed version of the managed package by default.

Setting the Salesforce API Version for Classes and Triggers


To set the Salesforce.com API and Apex version for a class or trigger:
1. Edit either a class or trigger, and click Version Settings.
2. Select the Version of the Salesforce.com API. This is also the version of Apex associated with the class or trigger.
3. Click Save.
If you pass an object as a parameter in a method call from one Apex class, C1, to another class, C2, and C2 has different fields
exposed due to the Salesforce.com API version setting, the fields in the objects are controlled by the version settings of C2.

151

Classes, Objects, and Interfaces

Setting Package Versions for Apex Classes and Triggers

Using the following example, the Categories field is set to null after calling the insertIdea method in class C2 from
a method in the test class C1, because the Categories field is not available in version 13.0 of the API.
The first class is saved using Salesforce.com API version 13.0:
// This class is saved using Salesforce API version 13.0
// Version 13.0 does not include the Idea.categories field
global class C2
{
global Idea insertIdea(Idea a) {
insert a; // category field set to null on insert
// retrieve the new idea
Idea insertedIdea = [SELECT title FROM Idea WHERE Id =:a.Id];
return insertedIdea;
}
}

The following class is saved using Salesforce.com API version 16.0:


@isTest
// This class is bound to API version 16.0 by Version Settings
private class C1
{
static testMethod void testC2Method() {
Idea i = new Idea();
i.CommunityId = '09aD000000004YCIAY';
i.Title = 'Testing Version Settings';
i.Body = 'Categories field is included in API version 16.0';
i.Categories = 'test';
C2 c2 = new C2();
Idea returnedIdea = c2.insertIdea(i);
// retrieve the new idea
Idea ideaMoreFields = [SELECT title, categories FROM Idea
WHERE Id = :returnedIdea.Id];
// assert that the categories field from the object created
// in this class is not null
System.assert(i.Categories != null);
// assert that the categories field created in C2 is null
System.assert(ideaMoreFields.Categories == null);
}
}

Setting Package Versions for Apex Classes and Triggers


To configure the package version settings for a class or trigger:
1. Edit either a class or trigger, and click Version Settings.
2. Select a Version for each managed package referenced by the class or trigger. This version of the managed package will
continue to be used by the class or trigger if later versions of the managed package are installed, unless you manually update
the version setting. To add an installed managed package to the settings list, select a package from the list of available
packages. The list is only displayed if you have an installed managed package that is not already associated with the class
or trigger.
3. Click Save.
Note the following when working with package version settings:

152

Classes, Objects, and Interfaces

Setting Package Versions for Apex Classes and Triggers

If you save an Apex class or trigger that references a managed package without specifying a version of the managed package,
the Apex class or trigger is associated with the latest installed version of the managed package by default.
You cannot Remove a class or trigger's version setting for a managed package if the package is referenced in the class or
trigger. Use Show Dependencies to find where a managed package is referenced by a class or trigger.

153

Chapter 5
Testing Apex
In this chapter ...

Understanding Testing in Apex


Unit Testing Apex
Running Unit Test Methods
Testing Best Practices
Testing Example

Apex provides a testing framework that allows you to write unit tests, run your
tests, check test results, and have code coverage results.
This chapter provides an overview of unit tests, data visibility for tests, as well as
the tools that are available on the Force.com platform for testing Apex.

Understanding Testing in Apex


Unit Testing Apex
Running Unit Test Methods
Testing Best Practices
Testing Example

154

Testing Apex

Understanding Testing in Apex

Understanding Testing in Apex


Testing is the key to successful long term development, and is a critical component of the development process. We strongly
recommend that you use a test-driven development process, that is, test development that occurs at the same time as code
development.

Why Test Apex?


Testing is key to the success of your application, particularly if your application is to be deployed to customers. If you validate
that your application works as expected, that there are no unexpected behaviors, your customers are going to trust you more.
There are two ways of testing an application. One is through the Salesforce user interface, important, but merely testing
through the user interface will not catch all of the use cases for your application. The other way is to test for bulk functionality:
up to 200 records can be passed through your code if it's invoked using SOAP API or by a Visualforce standard set controller.
An application is seldom finished. You will have additional releases of it, where you change and extend functionality. If you
have written comprehensive tests, you can ensure that a regression is not introduced with any new functionality.
Before you can deploy your code or package it for the Force.com AppExchange, the following must be true:

75% of your Apex code must be covered by unit tests, and all of those tests must complete successfully.
Note the following:

When deploying to a production organization, every unit test in your organization namespace is executed.
Calls to System.debug are not counted as part of Apex code coverage.
Test methods and test classes are not counted as part of Apex code coverage.
While only 75% of your Apex code must be covered by tests, your focus shouldn't be on the percentage of code that is
covered. Instead, you should make sure that every use case of your application is covered, including positive and negative
cases, as well as bulk and single record. This should lead to 75% or more of your code being covered by unit tests.

Every trigger has some test coverage.


All classes and triggers compile successfully.

Salesforce runs all tests in all organizations that have Apex code to verify that no behavior has been altered as a result of any
service upgrades.

What to Test in Apex


Salesforce.com recommends that you write tests for the following:
Single action
Test to verify that a single record produces the correct, expected result.
Bulk actions
Any Apex code, whether a trigger, a class or an extension, may be invoked for 1 to 200 records. You must test not only
the single record case, but the bulk cases as well.
Positive behavior
Test to verify that the expected behavior occurs through every expected permutation, that is, that the user filled out
everything correctly and did not go past the limits.

155

Testing Apex

Unit Testing Apex

Negative behavior
There are likely limits to your applications, such as not being able to add a future date, not being able to specify a negative
amount, and so on. You must test for the negative case and verify that the error messages are correctly produced as well
as for the positive, within the limits cases.
Restricted user
Test whether a user with restricted access to the sObjects used in your code sees the expected behavior. That is, whether
they can run the code or receive error messages.
Note: Conditional and ternary operators are not considered executed unless both the positive and negative branches
are executed.
For examples of these types of tests, see Testing Example on page 166.

Unit Testing Apex


To facilitate the development of robust, error-free code, Apex supports the creation and execution of unit tests. Unit tests are
class methods that verify whether a particular piece of code is working properly. Unit test methods take no arguments, commit
no data to the database, send no emails, and are flagged with the testMethod keyword in the method definition.
For example:
public class myClass {
static testMethod void myTest() {
code_block
}
}

Use the isTest annotation to define classes or individual methods that only contain code used for testing your application.
The isTest annotation is similar to creating methods declared as testMethod.
Note: Classes defined with the isTest annotation don't count against your organization limit of 2 MB for all Apex
code. Individual methods defined with the isTest annotation do count against your organization limits. See
Understanding Execution Governors and Limits on page 222.
This is an example of a test class that contains two test methods.
@isTest
private class MyTestClass {
// Methods for testing
@isTest static void test1() {
// Implement test code
}
@isTest static void test2() {
// Implement test code
}
}

156

Testing Apex

Isolation of Test Data from Organization Data in Unit Tests

Unit Test Considerations


Here are some things to note about unit tests.

Test methods cant be used to test Web service callouts. Web service callouts are asynchronous, while unit tests are
synchronous.
You cant send email messages from a test method.
Since test methods dont commit data created in the test, you dont have to delete test data upon completion.
Tracked changes for a record (FeedTrackedChange records) in Chatter feeds aren't available when test methods modify
the associated record. FeedTrackedChange records require the change to the parent record they're associated with to be
committed to the database before they're created. Since test methods don't commit data, they don't result in the creation
of FeedTrackedChange records.

See Also:
IsTest Annotation

Isolation of Test Data from Organization Data in Unit Tests


Starting with Apex code saved using Salesforce.com API version 24.0 and later, test methods dont have access by default to
pre-existing data in the organization, such as standard objects, custom objects, and custom settings data, and can only access
data that they create. However, objects that are used to manage your organization or metadata objects can still be accessed in
your tests such as:

User
Profile
Organization
RecordType
ApexClass
ApexTrigger
ApexComponent
ApexPage

Whenever possible, you should create test data for each test. You can disable this restriction by annotating your test class or
test method with the IsTest(SeeAllData=true) annotation. For more information, see IsTest(SeeAllData=true)
Annotation.
Test code saved using Salesforce.com API version 23.0 or earlier continues to have access to all data in the organization and
its data access is unchanged.
Data Access Considerations

If a new test method saved using Salesforce.com API version 24.0 or later calls a method in another class saved using
version 23.0 or earlier, the data access restrictions of the caller are enforced in the called method; that is, the called
method wont have access to organization data because the caller doesnt, even though it was saved in an earlier
version.
This access restriction to test data applies to all code running in test context. For example, if a test method causes a
trigger to execute and the test cant access organization data, the trigger wont be able to either.
If a test makes a Visualforce request, the executing test stays in test context but runs in a different thread, so test data
isolation is no longer enforced. In this case, the test will be able to access all data in the organization after initiating

157

Testing Apex

Using the runAs Method

the Visualforce request. However, if the Visualforce request performs a callback, such as a JavaScript remoting call,
any data inserted by the callback won't be visible to the test.
There might be some cases where you cant create certain types of data from your test method because of specific
limitations. Here are some examples of such limitations.
Inserting a pricebook entry for a product isnt feasible from a test since the standard pricebook isnt accessible
and cant be created in a running test. Also, inserting a pricebook entry for a custom pricebook isnt supported
since this requires defining a standard pricebook. For such situations, annotate your test method with
IsTest(SeeAllData=true) so that your test can access organization data.
Some standard objects arent createable. For more information on these objects, see the Object Reference for Salesforce
and Force.com.
Records that are created only after related records are committed to the database, like tracked changes in Chatter.
Tracked changes for a record (FeedTrackedChange records) in Chatter feeds aren't available when test methods
modify the associated record. FeedTrackedChange records require the change to the parent record they're associated
with to be committed to the database before they're created. Since test methods don't commit data, they don't
result in the creation of FeedTrackedChange records.

Using the runAs Method


Generally, all Apex code runs in system mode, and the permissions and record sharing of the current user are not taken into
account. The system method runAs enables you to write test methods that change either the user contexts to an existing user
or a new user, or to run using the code from a specific version of a managed package. When running as a user, all of that user's
record sharing is then enforced. You can only use runAs in a test method. The original system context is started again after
all runAs test methods complete. For information on using the runAs method and specifying a package version context, see
Testing Behavior in Package Versions on page 232.
Note: Every call to runAs counts against the total number of DML statements issued in the process.

In the following example, a new test user is created, then code is run as that user, with that user's permissions and record
access:
public class TestRunAs {
public static testMethod void testRunAs() {
// Setup test data
// This code runs as the system user
Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
User u = new User(Alias = 'standt', Email='[email protected]',
EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
LocaleSidKey='en_US', ProfileId = p.Id,
TimeZoneSidKey='America/Los_Angeles', UserName='[email protected]');
System.runAs(u) {
// The following code runs as user 'u'
System.debug('Current User: ' + UserInfo.getUserName());
System.debug('Current Profile: ' + UserInfo.getProfileId()); }
}
}

158

Testing Apex

Using Limits, startTest, and stopTest

You can nest more than one runAs method. For example:
public class TestRunAs2 {
public static testMethod void test2() {
Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
User u2 = new User(Alias = 'newUser', Email='[email protected]',
EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
LocaleSidKey='en_US', ProfileId = p.Id,
TimeZoneSidKey='America/Los_Angeles', UserName='[email protected]');
System.runAs(u2) {
// The following code runs as user u2.
System.debug('Current User: ' + UserInfo.getUserName());
System.debug('Current Profile: ' + UserInfo.getProfileId());
// The following code runs as user u3.
User u3 = [SELECT Id FROM User WHERE UserName='[email protected]'];
System.runAs(u3) {
System.debug('Current User: ' + UserInfo.getUserName());
System.debug('Current Profile: ' + UserInfo.getProfileId());
}
// Any additional code here would run as user u2.
}
}
}

Best Practices for Using runAs


The following items use the permissions granted by the user specified with runAs running as a specific user:

Dynamic Apex
Methods using with sharing or without sharing
Shared records

The original permissions are reset after runAs completes.


The runAs method ignores user license limits. You can create new users with runAs even if your organization has no additional
user licenses.

Using Limits, startTest, and stopTest


The Limits methods return the specific limit for the particular governor, such as the number of calls of a method or the amount
of heap size remaining.
There are two versions of every method: the first returns the amount of the resource that has been used in the current context,
while the second version contains the word limit and returns the total amount of the resource that is available for that context.
For example, getCallouts returns the number of callouts to an external service that have already been processed in the
current context, while getLimitCallouts returns the total number of callouts available in the given context.
In addition to the Limits methods, use the startTest and stopTest methods to validate how close the code is to reaching
governor limits.
The startTest method marks the point in your test code when your test actually begins. Each testMethod is allowed to
call this method only once. All of the code before this method should be used to initialize variables, populate data structures,
and so on, allowing you to set up everything you need to run your test. Any code that executes after the call to startTest
and before stopTest is assigned a new set of governor limits.

159

Testing Apex

Adding SOSL Queries to Unit Tests

The startTest method does not refresh the context of the test: it adds a context to your test. For example, if your class
makes 98 SOQL queries before it calls startTest, and the first significant statement after startTest is a DML statement,
the program can now make an additional 100 queries. Once stopTest is called, however, the program goes back into the
original context, and can only make 2 additional SOQL queries before reaching the limit of 100.
The stopTest method marks the point in your test code when your test ends. Use this method in conjunction with the
startTest method. Each testMethod is allowed to call this method only once. Any code that executes after the stopTest
method is assigned the original limits that were in effect before startTest was called. All asynchronous calls made after the
startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously.

Adding SOSL Queries to Unit Tests


To ensure that test methods always behave in a predictable way, any Salesforce Object Search Language (SOSL) query that
is added to an Apex test method returns an empty set of search results when the test method executes. If you do not want the
query to return an empty list of results, you can use the Test.setFixedSearchResults system method to define a list of
record IDs that are returned by the search. All SOSL queries that take place later in the test method return the list of record
IDs that were specified by the Test.setFixedSearchResults method. Additionally, the test method can call
Test.setFixedSearchResults multiple times to define different result sets for different SOSL queries. If you do not
call the Test.setFixedSearchResults method in a test method, or if you call this method without specifying a list of
record IDs, any SOSL queries that take place later in the test method return an empty list of results.
The list of record IDs specified by the Test.setFixedSearchResults method replaces the results that would normally
be returned by the SOSL query if it were not subject to any WHERE or LIMIT clauses. If these clauses exist in the SOSL query,
they are applied to the list of fixed search results. For example:
public class SoslFixedResultsTest1 {
public static testMethod void testSoslFixedResults() {
Id [] fixedSearchResults= new Id[1];
fixedSearchResults[0] = '001x0000003G89h';
Test.setFixedSearchResults(fixedSearchResults);
List<List<SObject>> searchList = [FIND 'test'
IN ALL FIELDS RETURNING
Account(id, name WHERE name = 'test' LIMIT 1)];
}
}

Although the account record with an ID of 001x0000003G89h may not match the query string in the FIND clause ('test'),
the record is passed into the RETURNING clause of the SOSL statement. If the record with ID 001x0000003G89h matches
the WHERE clause filter, the record is returned. If it does not match the WHERE clause, no record is returned.

Running Unit Test Methods


You can run unit tests for:

A specific class
A subset of classes
All unit tests in your organization

To run a test, use any of the following:

160

Testing Apex

Running Unit Test Methods

The Salesforce user interface


The Force.com IDE
The API

Running Tests Through the Salesforce User Interface


You can run unit tests on the Apex Test Execution page. Tests started on this page run asynchronously, that is, you don't have
to wait for a test class execution to finish. The Apex Test Execution page refreshes the status of a test and displays the results
after the test completes.

To use the Apex Test Execution page:


1. Click Your Name > Setup > Develop > Apex Test Execution.
2. Click Select Tests....
Note: If you have Apex classes that are installed from a managed package, you must compile these classes first by
clicking Compile all classes on the Apex Classes page so that they appear in the list. See Managing Apex Classes
in the online help.
3. Select the tests to run. The list of tests contains classes that contain test methods.

To select tests from an installed managed package, select its corresponding namespace from the drop-down list. Only
the classes of the managed package with the selected namespace appear in the list.
To select tests that exist locally in your organization, select [My Namespace] from the drop-down list. Only local
classes that aren't from managed packages appear in the list.
To select any test, select [All Namespaces] from the drop-down list. All the classes in the organization appear, whether
or not they are from a managed package.
Note: Classes whose tests are still running don't appear in the list.

4. Click Run.
After you run tests using the Apex Test Execution page, you can display the percentage of code covered by those tests on the
list of Apex classes. Click Your Name > Setup > Develop > Apex Classes, then click Calculate your organization's code
coverage.
Note: The code coverage value computed by Calculate your organization's code coverage might differ from the code
coverage value computed after running all unit tests using Run All Tests. This is because Calculate your organization's
code coverage excludes classes that are part of installed managed packages while Run All Tests doesn't.

161

Testing Apex

Running Unit Test Methods

You can also verify which lines of code are covered by tests for an individual class. Click Your Name > Setup > Develop >
Apex Classes, then click the percentage number in the Code Coverage column for a class.
Click Your Name > Setup > Develop > Apex Test Execution > View Test History to view all test results for your organization,
not just tests that you have run. Test results are retained for 30 days after they finish running, unless cleared.
Alternatively, use the Apex classes page to run tests.
To use the Apex Classes page to generate test results, click Your Name > Setup > Develop > Apex Classes, then either click
Run All Tests or click the name of a specific class that contains tests and click Run Test.
After you use the Apex Classes page to generate test results, the test result page contains the following sections. Each section
can be expanded or collapsed.

A summary section that details the number of tests run, the number of failures, the percentage of Apex code that is covered
by unit tests, the total execution time in milliseconds, and a link to a downloadable debug log file.
The debug log is automatically set to specific log levels and categories, which can't be changed.
Category

Level

Database

INFO

Apex Code

FINE

Apex Profiling

FINE

Workflow

FINEST

Validation

INFO

Important: Before you can deploy Apex or package it for the Force.com AppExchange, the following must be
true:
75% of your Apex code must be covered by unit tests, and all of those tests must complete successfully.
Note the following:
-

When deploying to a production organization, every unit test in your organization namespace is executed.
Calls to System.debug are not counted as part of Apex code coverage.
Test methods and test classes are not counted as part of Apex code coverage.
While only 75% of your Apex code must be covered by tests, your focus shouldn't be on the percentage of
code that is covered. Instead, you should make sure that every use case of your application is covered,
including positive and negative cases, as well as bulk and single record. This should lead to 75% or more
of your code being covered by unit tests.

Every trigger has some test coverage.


All classes and triggers compile successfully.

Test successes, if any.


Test failures, if any.
A code coverage section.
This section lists all the classes and triggers in your organization, and the percentage of lines of code in each class and
trigger that are covered by tests. If you click the coverage percent number, a page displays, highlighting all the lines of code
for that class or trigger that are covered by tests in blue, as well as highlighting all the lines of code that are not covered by
tests in red. It also lists how many times a particular line in the class or trigger was executed by the test

Test coverage warnings, if any.

162

Testing Apex

Running Unit Test Methods

Running Tests Using the Force.com IDE


In addition, you can execute tests with the Force.com IDE (see
https://wiki.developerforce.com/index.php/Apex_Toolkit_for_Eclipse).

Running Tests Using the API


Note: The API for asynchronous test runs is a Beta release.

Using objects and Apex code to insert and query those objects, you can add tests to the Apex job queue for execution and
check the results of completed test runs. This enables you to not only start tests asynchronously but also schedule your tests
to execute at specific times by using the Apex scheduler. See Apex Scheduler on page 98 for more information.
To start an asynchronous execution of unit tests and check their results, use these objects:

ApexTestQueueItem: Represents a single Apex class in the Apex job queue.


ApexTestResult: Represents the result of an Apex test method execution.

Insert an ApexTestQueueItem object to place its corresponding Apex class in the Apex job queue for execution. The Apex
job executes the test methods in the class. After the job executes, ApexTestResult contains the result for each single test
method executed as part of the test.
To abort a class that is in the Apex job queue, perform an update operation on the ApexTestQueueItem object and set its
Status field to Aborted.
If you insert multiple Apex test queue items in a single bulk operation, the queue items will share the same parent job. This
means that a test run can consist of the execution of the tests of several classes if all the test queue items are inserted in the
same bulk operation.
The maximum number of test queue items, and hence classes, that you can insert in the Apex job queue is the greater of 500
or 10 multiplied by the number of test classes in the organization.
This example shows how to use DML operations to insert and query the ApexTestQueueItem and ApexTestResult
objects. The enqueueTests method inserts queue items for all classes that end with Test. It then returns the parent job ID
of one queue item, which is the same for all queue items because they were inserted in bulk. The checkClassStatus method
retrieves all the queue items that correspond to the specified job ID. It then queries and outputs the name, job status, and pass
rate for each class. The checkMethodStatus method gets information of each test method that was executed as part of the
job.
public class TestUtil {
// Enqueue all classes ending in "Test".
public static ID enqueueTests() {
ApexClass[] testClasses =
[SELECT Id FROM ApexClass
WHERE Name LIKE '%Test'];
if (testClasses.size() > 0) {
ApexTestQueueItem[] queueItems = new List<ApexTestQueueItem>();
for (ApexClass cls : testClasses) {
queueItems.add(new ApexTestQueueItem(ApexClassId=cls.Id));
}
insert queueItems;
// Get the job ID of the first queue item returned.
ApexTestQueueItem item =
[SELECT ParentJobId FROM ApexTestQueueItem
WHERE Id=:queueItems[0].Id LIMIT 1];
return item.parentjobid;

163

Testing Apex

Running Unit Test Methods

}
return null;
}
// Get the status and pass rate for each class
// whose tests were run by the job.
// that correspond to the specified job ID.
public static void checkClassStatus(ID jobId) {
ApexTestQueueItem[] items =
[SELECT ApexClass.Name, Status, ExtendedStatus
FROM ApexTestQueueItem
WHERE ParentJobId=:jobId];
for (ApexTestQueueItem item : items) {
String extStatus = item.extendedstatus == null ? '' : item.extendedStatus;
System.debug(item.ApexClass.Name + ': ' + item.Status + extStatus);
}
}
// Get the result for each test method that was executed.
public static void checkMethodStatus(ID jobId) {
ApexTestResult[] results =
[SELECT Outcome, ApexClass.Name, MethodName, Message, StackTrace
FROM ApexTestResult
WHERE AsyncApexJobId=:jobId];
for (ApexTestResult atr : results) {
System.debug(atr.ApexClass.Name + '.' + atr.MethodName + ': ' + atr.Outcome);
if (atr.message != null) {
System.debug(atr.Message + '\n at ' + atr.StackTrace);
}
}
}
}

You can also use the runTests() call from the SOAP API to run tests synchronously:
RunTestsResult[] runTests(RunTestsRequest ri)

This call allows you to run all tests in all classes, all tests in a specific namespace, or all tests in a subset of classes in a specific
namespace, as specified in the RunTestsRequest object. It returns the following:

Total number of tests that ran


Code coverage statistics (described below)
Error information for each failed test
Information for each test that succeeds
Time it took to run the test

For more information on runTests(), see the WSDL located at


https://your_salesforce_server/services/wsdl/apex, where your_salesforce_server is equivalent to the
server on which your organization is located, such as na1.salesforce.com.

Though administrators in a Salesforce production organization cannot make changes to Apex code using the Salesforce user
interface, it is still important to use runTests() to verify that the existing unit tests run to completion after a change is made,
such as adding a unique constraint to an existing field. Salesforce production organizations must use the compileAndTest
SOAP API call to make changes to Apex code. For more information, see Deploying Apex on page 560.
For more information on runTests(), see SOAP API and SOAP Headers for Apex on page 590.

164

Testing Apex

Testing Best Practices

Testing Best Practices


Good tests should do the following:

Cover as many lines of code as possible. Before you can deploy Apex or package it for the Force.com AppExchange, the
following must be true:
Important:
75% of your Apex code must be covered by unit tests, and all of those tests must complete successfully.
Note the following:
-

When deploying to a production organization, every unit test in your organization namespace is executed.
Calls to System.debug are not counted as part of Apex code coverage.
Test methods and test classes are not counted as part of Apex code coverage.
While only 75% of your Apex code must be covered by tests, your focus shouldn't be on the percentage of
code that is covered. Instead, you should make sure that every use case of your application is covered,
including positive and negative cases, as well as bulk and single record. This should lead to 75% or more
of your code being covered by unit tests.

Every trigger has some test coverage.


All classes and triggers compile successfully.

In the case of conditional logic (including ternary operators), execute each branch of code logic.
Make calls to methods using both valid and invalid inputs.
Complete successfully without throwing any exceptions, unless those errors are expected and caught in a trycatch
block.
Always handle all exceptions that are caught, instead of merely catching the exceptions.
Use System.assert methods to prove that code behaves properly.
Use the runAs method to test your application in different user contexts.
Use the isTest annotation. Classes defined with the isTest annotation do not count against your organization limit of
2 MB for all Apex code. See IsTest Annotation on page 136.
Exercise bulk trigger functionalityuse at least 20 records in your tests.
Use the ORDER BY keywords to ensure that the records are returned in the expected order.
Not assume that record IDs are in sequential order.
Record IDs are not created in ascending order unless you insert multiple records with the same request. For example, if
you create an account A, and receive the ID 001D000000IEEmT, then create account B, the ID of account B may or may
not be sequentially higher.

On the list of Apex classes, there is a Code Coverage column. If you click the coverage percent number, a page displays,
highlighting all the lines of code for that class or trigger that are covered by tests in blue, as well as highlighting all the
lines of code that are not covered by tests in red. It also lists how many times a particular line in the class or trigger was
executed by the test
Set up test data:
Create the necessary data in test classes, so the tests do not have to rely on data in a particular organization.
Create all test data before calling the starttest method.
Since tests don't commit, you won't need to delete any data.

165

Testing Apex

Testing Example

Write comments stating not only what is supposed to be tested, but the assumptions the tester made about the data, the
expected outcome, and so on.
Test the classes in your application individually. Never test your entire application in a single test.

If you are running many tests, consider the following:

In the Force.com IDE, you may need to increase the Read timeout value for your Apex project. See
https://wiki.developerforce.com/index.php/Apex_Toolkit_for_Eclipse for details.
In the Salesforce user interface, you may need to test the classes in your organization individually, instead of trying to run
all of the tests at the same time using the Run All Tests button.

Testing Example
The following example includes cases for the following types of tests:

Positive case with single and multiple records


Negative case with single and multiple records
Testing with other users

The test is used with a simple mileage tracking application. The existing code for the application verifies that not more than
500 miles are entered in a single day. The primary object is a custom object named Mileage__c. Here is the entire test class.
The following sections step through specific portions of the code.
@isTest
private class MileageTrackerTestSuite {
static testMethod void runPositiveTestCases() {
Double totalMiles = 0;
final Double maxtotalMiles = 500;
final Double singletotalMiles = 300;
final Double u2Miles = 100;
//Set up user
User u1 = [SELECT Id FROM User WHERE Alias='auser'];
//Run As U1
System.RunAs(u1){
System.debug('Inserting 300

miles... (single record validation)');

Mileage__c testMiles1 = new Mileage__c(Miles__c = 300, Date__c = System.today());


insert testMiles1;
//Validate single insert
for(Mileage__c m:[SELECT miles__c FROM Mileage__c
WHERE CreatedDate = TODAY
and CreatedById = :u1.id
and miles__c != null]) {
totalMiles += m.miles__c;
}
System.assertEquals(singletotalMiles, totalMiles);

166

Testing Apex

Testing Example

//Bulk validation
totalMiles = 0;
System.debug('Inserting 200 mileage records... (bulk validation)');
List<Mileage__c> testMiles2 = new List<Mileage__c>();
for(integer i=0; i<200; i++) {
testMiles2.add( new Mileage__c(Miles__c = 1, Date__c = System.today()) );
}
insert testMiles2;
for(Mileage__c m:[SELECT miles__c FROM Mileage__c
WHERE CreatedDate = TODAY
and CreatedById = :u1.Id
and miles__c != null]) {
totalMiles += m.miles__c;
}
System.assertEquals(maxtotalMiles, totalMiles);
}//end RunAs(u1)
//Validate additional user:
totalMiles = 0;
//Setup RunAs
User u2 = [SELECT Id FROM User WHERE Alias='tuser'];
System.RunAs(u2){
Mileage__c testMiles3 = new Mileage__c(Miles__c = 100, Date__c = System.today());
insert testMiles3;
for(Mileage__c m:[SELECT miles__c FROM Mileage__c
WHERE CreatedDate = TODAY
and CreatedById = :u2.Id
and miles__c != null]) {
totalMiles += m.miles__c;
}
//Validate
System.assertEquals(u2Miles, totalMiles);
} //System.RunAs(u2)
} // runPositiveTestCases()
static testMethod void runNegativeTestCases() {
User u3 = [SELECT Id FROM User WHERE Alias='tuser'];
System.RunAs(u3){
System.debug('Inserting a record with 501 miles... (negative test case)');
Mileage__c testMiles3 = new Mileage__c( Miles__c = 501, Date__c = System.today() );
try {
insert testMiles3;
} catch (DmlException e) {
//Assert Error Message
System.assert( e.getMessage().contains('Insert failed. First exception on ' +
'row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, ' +
'Mileage request exceeds daily limit(500): [Miles__c]'),
e.getMessage() );
//Assert field
System.assertEquals(Mileage__c.Miles__c, e.getDmlFields(0)[0]);
//Assert Status Code

167

Testing Apex

Testing Example

System.assertEquals('FIELD_CUSTOM_VALIDATION_EXCEPTION' ,
e.getDmlStatusCode(0) );
} //catch
} //RunAs(u3)
} // runNegativeTestCases()
} // class MileageTrackerTestSuite

Positive Test Case


The following steps through the above code, in particular, the positive test case for single and multiple records.
1. Add text to the debug log, indicating the next step of the code:
System.debug('Inserting 300 more miles...single record validation');

2. Create a Mileage__c object and insert it into the database.


Mileage__c testMiles1 = new Mileage__c(Miles__c = 300, Date__c = System.today() );
insert testMiles1;

3. Validate the code by returning the inserted records:


for(Mileage__c m:[SELECT miles__c FROM Mileage__c
WHERE CreatedDate = TODAY
and CreatedById = :createdbyId
and miles__c != null]) {
totalMiles += m.miles__c;
}

4. Use the system.assertEquals method to verify that the expected result is returned:
System.assertEquals(singletotalMiles, totalMiles);

5. Before moving to the next test, set the number of total miles back to 0:
totalMiles = 0;

6. Validate the code by creating a bulk insert of 200 records.


First, add text to the debug log, indicating the next step of the code:
System.debug('Inserting 200 Mileage records...bulk validation');

7. Then insert 200 Mileage__c records:


List<Mileage__c> testMiles2 = new List<Mileage__c>();
for(Integer i=0; i<200; i++){
testMiles2.add( new Mileage__c(Miles__c = 1, Date__c = System.today()) );
}
insert testMiles2;

8. Use System.assertEquals to verify that the expected result is returned:


for(Mileage__c m:[SELECT miles__c FROM Mileage__c
WHERE CreatedDate = TODAY

168

Testing Apex

Testing Example

and CreatedById = :CreatedbyId


and miles__c != null]) {
totalMiles += m.miles__c;
}
System.assertEquals(maxtotalMiles, totalMiles);

Negative Test Case


The following steps through the above code, in particular, the negative test case.
1. Create a static test method called runNegativeTestCases:
static testMethod void runNegativeTestCases(){

2. Add text to the debug log, indicating the next step of the code:
System.debug('Inserting 501 miles... negative test case');

3. Create a Mileage__c record with 501 miles.


Mileage__c testMiles3 = new Mileage__c(Miles__c = 501, Date__c = System.today());

4. Place the insert statement within a try/catch block. This allows you to catch the validation exception and assert the
generated error message.
try {
insert testMiles3;
} catch (DmlException e) {

5. Now use the System.assert and System.assertEquals to do the testing. Add the following code to the catch
block you previously created:
//Assert Error Message
System.assert(e.getMessage().contains('Insert failed. First exception '+
'on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, '+
'Mileage request exceeds daily limit(500): [Miles__c]'),
e.getMessage());
//Assert Field
System.assertEquals(Mileage__c.Miles__c, e.getDmlFields(0)[0]);
//Assert Status Code
System.assertEquals('FIELD_CUSTOM_VALIDATION_EXCEPTION'
e.getDmlStatusCode(0));
}
}
}

Testing as a Second User


The following steps through the above code, in particular, running as a second user.
1. Before moving to the next test, set the number of total miles back to 0:
totalMiles = 0;

169

Testing Apex

Testing Example

2. Set up the next user.


User u2 = [SELECT Id FROM User WHERE Alias='tuser'];
System.RunAs(u2){

3. Add text to the debug log, indicating the next step of the code:
System.debug('Setting up testing - deleting any mileage records for ' +
UserInfo.getUserName() +
' from today');

4. Then insert one Mileage__c record:


Mileage__c testMiles3 = new Mileage__c(Miles__c = 100, Date__c = System.today());
insert testMiles3;

5. Validate the code by returning the inserted records:


for(Mileage__c m:[SELECT miles__c FROM Mileage__c
WHERE CreatedDate = TODAY
and CreatedById = :u2.Id
and miles__c != null]) {
totalMiles += m.miles__c;
}

6. Use the system.assertEquals method to verify that the expected result is returned:
System.assertEquals(u2Miles, totalMiles);

170

Chapter 6
Dynamic Apex
In this chapter ...

Understanding Apex Describe


Information
Dynamic SOQL
Dynamic SOSL
Dynamic DML

Dynamic Apex enables developers to create more flexible applications by providing


them with the ability to:

Access sObject and field describe information


Describe information provides information about sObject and field properties.
For example, the describe information for an sObject includes whether that
type of sObject supports operations like create or undelete, the sObject's name
and label, the sObject's fields and child objects, and so on. The describe
information for a field includes whether the field has a default value, whether
it is a calculated field, the type of the field, and so on.
Note that describe information provides information about objects in an
organization, not individual records.

Write dynamic SOQL queries, dynamic SOSL queries and dynamic DML
Dynamic SOQL and SOSL queries provide the ability to execute SOQL or
SOSL as a string at runtime, while dynamic DML provides the ability to
create a record dynamically and then insert it into the database using DML.
Using dynamic SOQL, SOSL, and DML, an application can be tailored
precisely to the organization as well as the user's permissions. This can be
useful for applications that are installed from Force.com AppExchange.

171

Dynamic Apex

Understanding Apex Describe Information

Understanding Apex Describe Information


Apex provides two data structures for sObject and field describe information:
Tokena lightweight, serializable reference to an sObject or a field that is validated at compile time.
Describe resultan object that contains all the describe properties for the sObject or field. Describe result objects are not
serializable, and are validated at runtime.

It is easy to move from a token to its describe result, and vice versa. Both sObject and field tokens have the method
getDescribe which returns the describe result for that token. On the describe result, the getSObjectType and
getSObjectField methods return the tokens for sObject and field, respectively.
Because tokens are lightweight, using them can make your code faster and more efficient. For example, use the token version
of an sObject or field when you are determining the type of an sObject or field that your code needs to use. The token can be
compared using the equality operator (==) to determine whether an sObject is the Account object, for example, or whether a
field is the Name field or a custom calculated field.
The following code provides a general example of how to use tokens and describe results to access information about sObject
and field properties:
// Create a new account as the generic type sObject
sObject s = new Account();
// Verify that the generic sObject is an Account sObject
System.assert(s.getsObjectType() == Account.sObjectType);
// Get the sObject describe result for the Account object
Schema.DescribeSObjectResult r = Account.sObjectType.getDescribe();
// Get the field describe result for the Name field on the Account object
Schema.DescribeFieldResult f = Schema.sObjectType.Account.fields.Name;
// Verify that the field token is the token for the Name field on an Account object
System.assert(f.getSObjectField() == Account.Name);
// Get the field describe result from the token
f = f.getSObjectField().getDescribe();

The following algorithm shows how you can work with describe information in Apex:
1.
2.
3.
4.

Generate a list or map of tokens for the sObjects in your organization (see Accessing All sObjects on page 175.)
Determine the sObject you need to access.
Generate the describe result for the sObject.
If necessary, generate a map of field tokens for the sObject (see Accessing All Field Describe Results for an sObject on
page 176.)
5. Generate the describe result for the field the code needs to access.

Understanding Describe Information Permissions


Apex generally runs in system mode. All classes and triggers that are not included in a package, that is, are native to your
organization, have no restrictions on the sObjects that they can look up dynamically. This means that with native code, you
can generate a map of all the sObjects for your organization, regardless of the current user's permission.
Dynamic Apex, contained in managed packages created by salesforce.com ISV partners that are installed from Force.com
AppExchange, have restricted access to any sObject outside the managed package. Partners can set the API Access value

172

Dynamic Apex

Understanding Apex Describe Information

within the package to grant access to standard sObjects not included as part of the managed package. While Partners can
request access to standard objects, custom objects are not included as part of the managed package and can never be referenced
or accessed by dynamic Apex that is packaged.
For more information, see About API and Dynamic Apex Access in Packages in the Salesforce online help.

Using sObject Tokens


SObjects, such as Account and MyCustomObject__c, act as static classes with special static methods and member variables
for accessing token and describe result information. You must explicitly reference an sObject and field name at compile time
to gain access to the describe result.
To access the token for an sObject, use one of the following methods:

Access the sObjectType member variable on an sObject type, such as Account.


Call the getSObjectType method on an sObject describe result, an sObject variable, a list, or a map.

Schema.SObjectType is the data type for an sObject token.

In the following example, the token for the Account sObject is returned:
Schema.sObjectType t = Account.sObjectType;

The following also returns a token for the Account sObject:


Account A = new Account();
Schema.sObjectType T = A.getSObjectType();

This example can be used to determine whether an sObject or a list of sObjects is of a particular type:
public class sObjectTest {
{
// Create a generic sObject variable s
SObject s = Database.query('SELECT Id FROM Account LIMIT 1');
// Verify if that sObject variable is an Account token
System.assertEquals(s.getSObjectType(), Account.sObjectType);
// Create a list of generic sObjects
List<sObject> l = new Account[]{};
// Verify if the list of sObjects contains Account tokens
System.assertEquals(l.getSObjectType(), Account.sObjectType);
}
}

Some standard sObjects have a field called sObjectType, for example, AssignmentRule, QueueSObject, and RecordType.
For these types of sObjects, always use the getSObjectType method for retrieving the token. If you use the property, for
example, RecordType.sObjectType, the field is returned.

Using sObject Describe Results


To access the describe result for an sObject, use one of the following methods:

Call the getDescribe method on an sObject token.


Use the Schema sObjectType static variable with the name of the sObject. For example, Schema.sObjectType.Lead.

Schema.DescribeSObjectResult is the data type for an sObject describe result.

173

Dynamic Apex

Understanding Apex Describe Information

The following example uses the getDescribe method on an sObject token:


Schema.DescribeSObjectResult D = Account.sObjectType.getDescribe();

The following example uses the Schema sObjectType static member variable:
Schema.DescribeSObjectResult D = Schema.SObjectType.Account;

For more information about the methods available with the sObject describe result, see sObject Describe Result Methods on
page 332.

Using Field Tokens


To access the token for a field, use one of the following methods:

Access the static member variable name of an sObject static type, for example, Account.Name.
Call the getSObjectField method on a field describe result.

The field token uses the data type Schema.SObjectField.


In the following example, the field token is returned for the Account object's AccountNumber field:
Schema.SObjectField F = Account.AccountNumber;

In the following example, the field token is returned from the field describe result:
// Get the describe result for the Name field on the Account object
Schema.DescribeFieldResult f = Schema.sObjectType.Account.fields.Name;
// Verify that the field token is the token for the Name field on an Account object
System.assert(f.getSObjectField() == Account.Name);
// Get the describe result from the token
f = f.getSObjectField().getDescribe();

Using Field Describe Results


To access the describe result for a field, use one of the following methods:

Call the getDescribe method on a field token.


Access the fields member variable of an sObject token with a field member variable (such as Name, BillingCity, and
so on.)

The field describe result uses the data type Schema.DescribeFieldResult.


The following example uses the getDescribe method:
Schema.DescribeFieldResult F = Account.AccountNumber.getDescribe();

This example uses the fields member variable method:


Schema.DescribeFieldResult F = Schema.SObjectType.Account.fields.Name;

In the example above, the system uses special parsing to validate that the final member variable (Name) is valid for the specified
sObject at compile time. When the parser finds the fields member variable, it looks backwards to find the name of the
sObject (Account) and validates that the field name following the fields member variable is legitimate. The fields
member variable only works when used in this manner.

174

Dynamic Apex

Understanding Apex Describe Information

You can only have 100 fields member variable statements in an Apex class or trigger.
Note: You should not use the fields member variable without also using either a field member variable name or
the getMap method. For more information on getMap, see Accessing All Field Describe Results for an sObject on
page 176.
For more information about the methods available with a field describe result, see Describe Field Result Methods on page
336.

Accessing All sObjects


Use the Schema getGlobalDescribe method to return a map that represents the relationship between all sObject names
(keys) to sObject tokens (values). For example:
Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();

The map has the following characteristics:

It is dynamic, that is, it is generated at runtime on the sObjects currently available for the organization, based on permissions.
The sObject names are case insensitive.
The keys use namespaces as required.
The keys reflect whether the sObject is a custom object.

For example, if the code block that generates the map is in namespace N1, and an sObject is also in N1, the key in the map
is represented as MyObject__c. However, if the code block is in namespace N1, and the sObject is in namespace N2, the
key is N2__MyObject__c.
In addition, standard sObjects have no namespace prefix.

Creating sObjects Dynamically


You can create sObjects whose types are determined at run time by calling the newSObject method of the
Schema.sObjectType sObject token class. The following example shows how to get an sObject token that corresponds to
an sObject type name using the Schema.getGlobalDescribe method. Then, an instance of the sObject is created through
the newSObject method of Schema.sObjectType. This example also contains a test method that verifies the dynamic
creation of an account.
public class DynamicSObjectCreation {
public static sObject createObject(String typeName) {
Schema.SObjectType targetType = Schema.getGlobalDescribe().get(typeName);
if (targetType == null) {
// throw an exception
}
// Instantiate an sObject with the type passed in as an argument
// at run time.
return targetType.newSObject();
}
static testmethod void testObjectCreation() {
String typeName = 'Account';
String acctName = 'Acme';
// Create a new sObject by passing the sObject type as an argument.
Account a = (Account)createObject(typeName);
System.assertEquals(typeName, String.valueOf(a.getSobjectType()));
// Set the account name and insert the account.
a.Name = acctName;
insert a;

175

Dynamic Apex

Understanding Apex Describe Information

// Verify the new sObject got inserted.


Account[] b = [SELECT Name from Account WHERE Name = :acctName];
system.assert(b.size() > 0);
}
}

Accessing All Field Describe Results for an sObject


Use the field describe result's getMap method to return a map that represents the relationship between all the field names
(keys) and the field tokens (values) for an sObject.
The following example generates a map that can be used to access a field by name:
Map<String, Schema.SObjectField> M = Schema.SObjectType.Account.fields.getMap();

Note: The value type of this map is not a field describe result. Using the describe results would take too many system
resources. Instead, it is a map of tokens that you can use to find the appropriate field. After you determine the field,
generate the describe result for it.
The map has the following characteristics:

It is dynamic, that is, it is generated at runtime on the fields for that sObject.
All field names are case insensitive.
The keys use namespaces as required.
The keys reflect whether the field is a custom object.

For example, if the code block that generates the map is in namespace N1, and a field is also in N1, the key in the map is
represented as MyField__c. However, if the code block is in namespace N1, and the field is in namespace N2, the key is
N2__MyField__c.
In addition, standard fields have no namespace prefix.

Accessing All Data Categories Associated with an sObject


Use the describeDataCategory Groups and describeDataCategory GroupStructures methods to return the
categories associated with a specific object:
1. Return all the category groups associated with the objects of your choice (see describeDataCategory Groups on page 324).
2. From the returned map, get the category group name and sObject name you want to further interrogate (see Schema.Describe
DataCategoryGroupResult on page 326).
3. Specify the category group and associated object, then retrieve the categories available to this object (see describeDataCategory
GroupStructures on page 325).
The describeDataCategory GroupStructures method returns the categories available for the object in the category
group you specified. For additional information about data categories, see What are Data Categories? in the Salesforce online
help.
In the following example, the describeDataCategoryGroupSample method returns all the category groups associated
with the Article and Question objects. The describeDataCategoryGroupStructures method returns all the categories
available for articles and questions in the Regions category group. For additional information about articles and questions, see
Managing Articles and Translations and Answers Overview in the Salesforce online help.
To use the following example, you must:

Enable Salesforce Knowledge.


Enable the answers feature.
Create a data category group called Regions.

176

Dynamic Apex

Understanding Apex Describe Information

Assign Regions as the data category group to be used by Answers.


Make sure the Regions data category group is assigned to Salesforce Knowledge.

For more information on creating data category groups, see Creating and Modifying Category Groups in the Salesforce
online help. For more information on answers, see Answers Overview in the Salesforce online help.

public class DescribeDataCategoryGroupSample {


public static List<DescribeDataCategoryGroupResult> describeDataCategoryGroupSample(){
List<DescribeDataCategoryGroupResult> describeCategoryResult;
try {
//Creating the list of sobjects to use for the describe
//call
List<String> objType = new List<String>();
objType.add('KnowledgeArticleVersion');
objType.add('Question');
//Describe Call
describeCategoryResult = Schema.describeDataCategoryGroups(objType);
//Using the results and retrieving the information
for(DescribeDataCategoryGroupResult singleResult : describeCategoryResult){
//Getting the name of the category
singleResult.getName();
//Getting the name of label
singleResult.getLabel();
//Getting description
singleResult.getDescription();
//Getting the sobject
singleResult.getSobject();
}
} catch(Exception e){
}
return describeCategoryResult;
}
}

public class DescribeDataCategoryGroupStructures {


public static List<DescribeDataCategoryGroupStructureResult>
getDescribeDataCategoryGroupStructureResults(){
List<DescribeDataCategoryGroupResult> describeCategoryResult;
List<DescribeDataCategoryGroupStructureResult> describeCategoryStructureResult;
try {
//Making the call to the describeDataCategoryGroups to
//get the list of category groups associated
List<String> objType = new List<String>();
objType.add('KnowledgeArticleVersion');
objType.add('Question');
describeCategoryResult = Schema.describeDataCategoryGroups(objType);
//Creating a list of pair objects to use as a parameter
//for the describe call
List<DataCategoryGroupSobjectTypePair> pairs =
new List<DataCategoryGroupSobjectTypePair>();
//Looping throught the first describe result to create
//the list of pairs for the second describe call
for(DescribeDataCategoryGroupResult singleResult :

177

Dynamic Apex

Understanding Apex Describe Information

describeCategoryResult){
DataCategoryGroupSobjectTypePair p =
new DataCategoryGroupSobjectTypePair();
p.setSobject(singleResult.getSobject());
p.setDataCategoryGroupName(singleResult.getName());
pairs.add(p);
}
//describeDataCategoryGroupStructures()
describeCategoryStructureResult =
Schema.describeDataCategoryGroupStructures(pairs, false);
//Getting data from the result
for(DescribeDataCategoryGroupStructureResult singleResult :
describeCategoryStructureResult){
//Get name of the associated Sobject
singleResult.getSobject();
//Get the name of the data category group
singleResult.getName();
//Get the name of the data category group
singleResult.getLabel();
//Get the description of the data category group
singleResult.getDescription();
//Get the top level categories
DataCategory [] toplevelCategories =
singleResult.getTopCategories();
//Recursively get all the categories
List<DataCategory> allCategories =
getAllCategories(toplevelCategories);
for(DataCategory category : allCategories) {
//Get the name of the category
category.getName();
//Get the label of the category
category.getLabel();
//Get the list of sub categories in the category
DataCategory [] childCategories =
category.getChildCategories();
}
}
} catch (Exception e){
}
return describeCategoryStructureResult;
}
private static DataCategory[] getAllCategories(DataCategory [] categories){
if(categories.isEmpty()){
return new DataCategory[]{};
} else {
DataCategory [] categoriesClone = categories.clone();
DataCategory category = categoriesClone[0];
DataCategory[] allCategories = new DataCategory[]{category};
categoriesClone.remove(0);
categoriesClone.addAll(category.getChildCategories());
allCategories.addAll(getAllCategories(categoriesClone));
return allCategories;
}
}
}

178

Dynamic Apex

Understanding Apex Describe Information

Testing Access to All Data Categories Associated with an sObject


The following example tests the describeDataCategoryGroupSample method shown in Accessing All Data Categories
Associated with an sObject. It ensures that the returned category group and associated objects are correct.
@isTest
private class DescribeDataCategoryGroupSampleTest {
public static testMethod void describeDataCategoryGroupSampleTest(){
List<DescribeDataCategoryGroupResult>describeResult =
DescribeDataCategoryGroupSample.describeDataCategoryGroupSample();
//Assuming that you have KnowledgeArticleVersion and Questions
//associated with only one category group 'Regions'.
System.assert(describeResult.size() == 2,
'The results should only contain two results: ' + describeResult.size());
for(DescribeDataCategoryGroupResult result : describeResult) {
//Storing the results
String name = result.getName();
String label = result.getLabel();
String description = result.getDescription();
String objectNames = result.getSobject();
//asserting the values to make sure
System.assert(name == 'Regions',
'Incorrect name was returned: ' + name);
System.assert(label == 'Regions of the World',
'Incorrect label was returned: ' + label);
System.assert(description == 'This is the category group for all the regions',
'Incorrect description was returned: ' + description);
System.assert(objectNames.contains('KnowledgeArticleVersion')
|| objectNames.contains('Question'),
'Incorrect sObject was returned: ' + objectNames);
}
}
}

This example tests the describeDataCategoryGroupStructures method shown in Accessing All Data Categories
Associated with an sObject. It ensures that the returned category group, categories and associated objects are correct.
@isTest
private class DescribeDataCategoryGroupStructuresTest {
public static testMethod void getDescribeDataCategoryGroupStructureResultsTest(){
List<Schema.DescribeDataCategoryGroupStructureResult> describeResult =
DescribeDataCategoryGroupStructures.getDescribeDataCategoryGroupStructureResults();
System.assert(describeResult.size() == 2,
'The results should only contain 2 results: ' + describeResult.size());
//Creating category info
CategoryInfo world = new CategoryInfo('World', 'World');
CategoryInfo asia = new CategoryInfo('Asia', 'Asia');
CategoryInfo northAmerica = new CategoryInfo('NorthAmerica',
'North America');
CategoryInfo southAmerica = new CategoryInfo('SouthAmerica',
'South America');
CategoryInfo europe = new CategoryInfo('Europe', 'Europe');
List<CategoryInfo> info = new CategoryInfo[] {
asia, northAmerica, southAmerica, europe
};
for (Schema.DescribeDataCategoryGroupStructureResult result : describeResult) {
String name = result.getName();

179

Dynamic Apex

Dynamic SOQL

String label = result.getLabel();


String description = result.getDescription();
String objectNames = result.getSobject();
//asserting the values to make sure
System.assert(name == 'Regions',
'Incorrect name was returned: ' + name);
System.assert(label == 'Regions of the World',
'Incorrect label was returned: ' + label);
System.assert(description == 'This is the category group for all the regions',
'Incorrect description was returned: ' + description);
System.assert(objectNames.contains('KnowledgeArticleVersion')
|| objectNames.contains('Question'),
'Incorrect sObject was returned: ' + objectNames);
DataCategory [] topLevelCategories = result.getTopCategories();
System.assert(topLevelCategories.size() == 1,
'Incorrect number of top level categories returned: ' + topLevelCategories.size());
System.assert(topLevelCategories[0].getLabel() == world.getLabel() &&
topLevelCategories[0].getName() == world.getName());
//checking if the correct children are returned
DataCategory [] children = topLevelCategories[0].getChildCategories();
System.assert(children.size() == 4,
'Incorrect number of children returned: ' + children.size());
for(Integer i=0; i < children.size(); i++){
System.assert(children[i].getLabel() == info[i].getLabel() &&
children[i].getName() == info[i].getName());
}
}
}
private class CategoryInfo {
private final String name;
private final String label;
private CategoryInfo(String n, String l){
this.name = n;
this.label = l;
}
public String getName(){
return this.name;
}
public String getLabel(){
return this.label;
}
}
}

Dynamic SOQL
Dynamic SOQL refers to the creation of a SOQL string at runtime with Apex code. Dynamic SOQL enables you to create
more flexible applications. For example, you can create a search based on input from an end user, or update records with varying
field names.
To create a dynamic SOQL query at runtime, use the database query method, in one of the following ways:

180

Dynamic Apex

Dynamic SOSL

Return a single sObject when the query returns a single record:


sObject S = Database.query(string_limit_1);

Return a list of sObjects when the query returns more than a single record:
List<sObject> L = Database.query(string);

The database query method can be used wherever an inline SOQL query can be used, such as in regular assignment statements
and for loops. The results are processed in much the same way as static SOQL queries are processed.
Dynamic SOQL results can be specified as concrete sObjects, such as Account or MyCustomObject__c, or as the generic
sObject data type. At runtime, the system validates that the type of the query matches the declared type of the variable. If the
query does not return the correct sObject type, a runtime error is thrown. This means you do not need to cast from a generic
sObject to a concrete sObject.
Dynamic SOQL queries have the same governor limits as static queries. For more information on governor limits, see
Understanding Execution Governors and Limits on page 222.
For a full description of SOQL query syntax, see Salesforce Object Query Language (SOQL) in the Force.com SOQL and
SOSL Reference.

SOQL Injection
SOQL injection is a technique by which a user causes your application to execute database methods you did not intend by
passing SOQL statements into your code. This can occur in Apex code whenever your application relies on end user input to
construct a dynamic SOQL statement and you do not handle the input properly.
To prevent SOQL injection, use the escapeSingleQuotes method. This method adds the escape character (\) to all single
quotation marks in a string that is passed in from a user. The method ensures that all single quotation marks are treated as
enclosing strings, instead of database commands.

Dynamic SOSL
Dynamic SOSL refers to the creation of a SOSL string at runtime with Apex code. Dynamic SOSL enables you to create more
flexible applications. For example, you can create a search based on input from an end user, or update records with varying
field names.
To create a dynamic SOSL query at runtime, use the search query method. For example:
List<List <sObject>> myQuery = search.query(SOSL_search_string);

The following example exercises a simple SOSL query string.


String searchquery='FIND\'Edge*\'IN ALL FIELDS RETURNING Account(id,name),Contact, Lead';
List<List<SObject>>searchList=search.query(searchquery);

Dynamic SOSL statements evaluate to a list of lists of sObjects, where each list contains the search results for a particular
sObject type. The result lists are always returned in the same order as they were specified in the dynamic SOSL query. From
the example above, the results from Account are first, then Contact, then Lead.

181

Dynamic Apex

Dynamic DML

The search query method can be used wherever an inline SOSL query can be used, such as in regular assignment statements
and for loops. The results are processed in much the same way as static SOSL queries are processed.
SOSL queries are only supported in Apex classes and anonymous blocks. You cannot use a SOSL query in a trigger.
Dynamic SOSL queries have the same governor limits as static queries. For more information on governor limits, see
Understanding Execution Governors and Limits on page 222.
For a full description of SOSL query syntax, see Salesforce Object Search Language (SOSL) in the Force.com SOQL and SOSL
Reference.

SOSL Injection
SOSL injection is a technique by which a user causes your application to execute database methods you did not intend by passing
SOSL statements into your code. This can occur in Apex code whenever your application relies on end user input to construct
a dynamic SOSL statement and you do not handle the input properly.
To prevent SOSL injection, use the escapeSingleQuotes method. This method adds the escape character (\) to all single
quotation marks in a string that is passed in from a user. The method ensures that all single quotation marks are treated as
enclosing strings, instead of database commands.

Dynamic DML
In addition to querying describe information and building SOQL queries at runtime, you can also create sObjects dynamically,
and insert them into the database using DML.
To create a new sObject of a given type, use the newSObject method on an sObject token. Note that the token must be cast
into a concrete sObject type (such as Account). For example:
// Get a new account
Account A = new Account();
// Get the token for the account
Schema.sObjectType tokenA = A.getSObjectType();
// The following produces an error because the token is a generic sObject, not an Account
// Account B = tokenA.newSObject();
// The following works because the token is cast back into an Account
Account B = (Account)tokenA.newSObject();

Though the sObject token tokenA is a token of Account, it is considered an sObject because it is accessed separately. It must
be cast back into the concrete sObject type Account to use the newSObject method. For more information on casting, see
Classes and Casting on page 142.
This is another example that shows how to obtain the sObject token through the Schema.getGlobalDescribe method
and then creates a new sObject using the newSObject method on the token. This example also contains a test method that
verifies the dynamic creation of an account.
public class DynamicSObjectCreation {
public static sObject createObject(String typeName) {
Schema.SObjectType targetType = Schema.getGlobalDescribe().get(typeName);
if (targetType == null) {
// throw an exception
}
// Instantiate an sObject with the type passed in as an argument
// at run time.
return targetType.newSObject();

182

Dynamic Apex

Dynamic DML

}
static testmethod void testObjectCreation() {
String typeName = 'Account';
String acctName = 'Acme';
// Create a new sObject by passing the sObject type as an argument.
Account a = (Account)createObject(typeName);
System.assertEquals(typeName, String.valueOf(a.getSobjectType()));
// Set the account name and insert the account.
a.Name = acctName;
insert a;
// Verify the new sObject got inserted.
Account[] b = [SELECT Name from Account WHERE Name = :acctName];
system.assert(b.size() > 0);
}
}

You can also specify an ID with newSObject to create an sObject that references an existing record that you can update later.
For example:
SObject s = Database.query('SELECT Id FROM account LIMIT 1')[0].getSObjectType().
newSObject([SELECT Id FROM Account LIMIT 1][0].Id);

See Schema.sObjectType on page 342.

Setting and Retrieving Field Values


Use the get and put methods on an object to set or retrieve values for fields using either the API name of the field expressed
as a String, or the field's token. In the following example, the API name of the field AccountNumber is used:
SObject s = [SELECT AccountNumber FROM Account LIMIT 1];
Object o = s.get('AccountNumber');
s.put('AccountNumber', 'abc');

The following example uses the AccountNumber field's token instead:


Schema.DescribeFieldResult f = Schema.sObjectType.Account.fields.AccountNumber;
Sobject s = Database.query('SELECT AccountNumber FROM Account LIMIT 1');
s.put(f.getsObjectField(), '12345');

The Object scalar data type can be used as a generic data type to set or retrieve field values on an sObject. This is equivalent
to the anyType field type. Note that the Object data type is different from the sObject data type, which can be used as a generic
type for any sObject.
Note: Apex classes and triggers saved (compiled) using API version 15.0 and higher produce a runtime error if you
assign a String value that is too long for the field.

Setting and Retrieving Foreign Keys


Apex supports populating foreign keys by name (or external ID) in the same way as the API. To set or retrieve the scalar ID
value of a foreign key, use the get or put methods.

183

Dynamic Apex

Dynamic DML

To set or retrieve the record associated with a foreign key, use the getSObject and putSObject methods. Note that these
methods must be used with the sObject data type, not Object. For example:
SObject c =
Database.query('SELECT Id, FirstName, AccountId, Account.Name FROM Contact LIMIT 1');
SObject a = c.getSObject('Account');

There is no need to specify the external ID for a parent sObject value while working with child sObjects. If you provide an
ID in the parent sObject, it is ignored by the DML operation. Apex assumes the foreign key is populated through a relationship
SOQL query, which always returns a parent object with a populated ID. If you have an ID, use it with the child object.
For example, suppose that custom object C1 has a foreign key c2__c that links to a child custom object C2. You want to
create a C1 object and have it associated with a C2 record named 'xxx' (assigned to the value c2__r). You do not need the
ID of the 'xxx' record, as it is populated through the relationship of parent to child. For example:
insert new C1__c(name = 'x', c2__r = new C2__c(name = 'xxx'));

If you had assigned a value to the ID for c2__r, it would be ignored. If you do have the ID, assign it to the object (c2__c),
not the record.
You can also access foreign keys using dynamic Apex. The following example shows how to get the values from a subquery in
a parent-to-child relationship using dynamic Apex:
String queryString = 'SELECT Id, Name, ' +
'(SELECT FirstName, LastName FROM Contacts LIMIT 1) FROM Account';
SObject[] queryParentObject = Database.query(queryString);
for (SObject parentRecord : queryParentObject){
Object ParentFieldValue = parentRecord.get('Name');
// Prevent a null relationship from being accessed
SObject[] childRecordsFromParent = parentRecord.getSObjects('Contacts');
if (childRecordsFromParent != null) {
for (SObject childRecord : childRecordsFromParent){
Object ChildFieldValue1 = childRecord.get('FirstName');
Object ChildFieldValue2 = childRecord.get('LastName');
System.debug('Account Name: ' + ParentFieldValue +
'. Contact Name: '+ ChildFieldValue1 + ' ' + ChildFieldValue2);
}
}
}

184

Chapter 7
Batch Apex
In this chapter ...

Using Batch Apex


Understanding Apex Managed
Sharing

A developer can now employ batch Apex to build complex, long-running processes
on the Force.com platform. For example, a developer could build an archiving
solution that runs on a nightly basis, looking for records past a certain date and
adding them to an archive. Or a developer could build a data cleansing operation
that goes through all Accounts and Opportunities on a nightly basis and updates
them if necessary, based on custom criteria.
Batch Apex is exposed as an interface that must be implemented by the developer.
Batch jobs can be programmatically invoked at runtime using Apex.
You can only have five queued or active batch jobs at one time. You can evaluate
your current count by viewing the Scheduled Jobs page in Salesforce or
programmatically using SOAP API to query the AsyncapexJob object.
Caution: Use extreme care if you are planning to invoke a batch job
from a trigger. You must be able to guarantee that the trigger will not
add more batch jobs than the five that are allowed. In particular, consider
API bulk updates, import wizards, mass record changes through the user
interface, and all cases where more than one record can be updated at a
time.
Batch jobs can also be programmatically scheduled to run at specific times using
the Apex scheduler, or scheduled using the Schedule Apex page in the Salesforce
user interface. For more information on the Schedule Apex page, see Scheduling
Apex in the Salesforce online help.
The batch Apex interface is also used for Apex managed sharing recalculations.
For more information on batch jobs, continue to Using Batch Apex on page 186.
For more information on Apex managed sharing, see Understanding Apex
Managed Sharing on page 194.

185

Batch Apex

Using Batch Apex

Using Batch Apex


To use batch Apex, you must write an Apex class that implements the Salesforce-provided interface Database.Batchable,
and then invoke the class programmatically.
To monitor or stop the execution of the batch Apex job, click Your Name > Setup > Monitoring > Apex Jobs. For more
information, see Monitoring the Apex Job Queue in the Salesforce online help.

Implementing the Database.Batchable Interface


The Database.Batchable interface contains three methods that must be implemented:

start method
global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc)
{}

The start method is called at the beginning of a batch Apex job. Use the start method to collect the records or objects
to be passed to the interface method execute. This method returns either a Database.QueryLocator object or an
iterable that contains the records or objects being passed into the job.
Use the Database.QueryLocator object when you are using a simple query (SELECT) to generate the scope of objects
used in the batch job. If you use a querylocator object, the governor limit for the total number of records retrieved by SOQL
queries is bypassed. For example, a batch Apex job for the Account object can return a QueryLocator for all account
records (up to 50 million records) in an organization. Another example is a sharing recalculation for the Contact object
that returns a QueryLocator for all account records in an organization.
Use the iterable when you need to create a complex scope for the batch job. You can also use the iterable to create your
own custom process for iterating through the list.
Important: If you use an iterable, the governor limit for the total number of records retrieved by SOQL queries
is still enforced.

execute method:
global void execute(Database.BatchableContext BC, list<P>){}

The execute method is called for each batch of records passed to the method. Use this method to do all required processing
for each chunk of data.
This method takes the following:
A reference to the Database.BatchableContext object.
A list of sObjects, such as List<sObject>, or a list of parameterized types. If you are using a
Database.QueryLocator, the returned list should be used.
Batches of records are not guaranteed to execute in the order they are received from the start method.

finish method
global void finish(Database.BatchableContext BC){}

The finish method is called after all batches are processed. Use this method to send confirmation emails or execute
post-processing operations.

186

Batch Apex

Using Batch Apex

Each execution of a batch Apex job is considered a discrete transaction. For example, a batch Apex job that contains 1,000
records and is executed without the optional scope parameter from Database.executeBatch is considered five transactions
of 200 records each. The Apex governor limits are reset for each transaction. If the first transaction succeeds but the second
fails, the database updates made in the first transaction are not rolled back.

Using Database.BatchableContext
All of the methods in the Database.Batchable interface require a reference to a Database.BatchableContext object.
Use this object to track the progress of the batch job.
The following is the instance method with the Database.BatchableContext object:
Name

Arguments

getJobID

Returns

Description

ID

Returns the ID of the AsyncApexJob object associated


with this batch job as a string. Use this method to track
the progress of records in the batch job. You can also
use this ID with the System.abortJob method.

The following example uses the Database.BatchableContext to query the AsyncApexJob associated with the batch
job.
global void finish(Database.BatchableContext BC){
// Get the ID of the AsyncApexJob representing this batch job
// from Database.BatchableContext.
// Query the AsyncApexJob object to retrieve the current job's information.
AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed,
TotalJobItems, CreatedBy.Email
FROM AsyncApexJob WHERE Id =
:BC.getJobId()];
// Send an email to the Apex job's submitter notifying of job completion.
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {a.CreatedBy.Email};
mail.setToAddresses(toAddresses);
mail.setSubject('Apex Sharing Recalculation ' + a.Status);
mail.setPlainTextBody
('The batch Apex job processed ' + a.TotalJobItems +
' batches with '+ a.NumberOfErrors + ' failures.');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}

Using Database.QueryLocator to Define Scope


The start method can return either a Database.QueryLocator object that contains the records to be used in the batch
job or an iterable.
The following example uses a Database.QueryLocator:
global class SearchAndReplace implements Database.Batchable<sObject>{
global
global
global
global

final
final
final
final

String
String
String
String

Query;
Entity;
Field;
Value;

global SearchAndReplace(String q, String e, String f, String v){


Query=q; Entity=e; Field=f;Value=v;
}

187

Batch Apex

Using Batch Apex

global Database.QueryLocator start(Database.BatchableContext BC){


return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<sObject> scope){
for(sobject s : scope){
s.put(Field,Value);
}
update scope;
}
global void finish(Database.BatchableContext BC){
}
}

Using an Iterable in Batch Apex to Define Scope


The start method can return either a Database.QueryLocator object that contains the records to be used in the batch
job, or an iterable. Use an iterable to step through the returned items more easily.
global class batchClass implements Database.batchable{
global Iterable start(Database.BatchableContext info){
return new CustomAccountIterable();
}
global void execute(Database.BatchableContext info, List<Account> scope){
List<Account> accsToUpdate = new List<Account>();
for(Account a : scope){
a.Name = 'true';
a.NumberOfEmployees = 70;
accsToUpdate.add(a);
}
update accsToUpdate;
}
global void finish(Database.BatchableContext info){
}
}

Using the Database.executeBatch Method


You can use the Database.executeBatch method to programmatically begin a batch job.
Important: When you call Database.executeBatch, Salesforce only adds the process to the queue at the scheduled
time. Actual execution may be delayed based on service availability.
The Database.executeBatch method takes two parameters:

The class that implements Database.Batchable.


The Database.executeBatch method takes an optional parameter scope. This parameter specifies the number of
records that should be passed into the execute method. This value must be greater than 0. There is no upper limit,
however, if you use a very high number, you may run into other limits. Use this when you have many operations for each
record being passed in and are running into governor limits. By limiting the number of records, you are thereby limiting
the operations per transaction.

The Database.executeBatch method returns the ID of the AsyncApexJob object, which can then be used to track the
progress of the job. For example:
ID batchprocessid = Database.executeBatch(reassign);
AsyncApexJob aaj = [SELECT Id, Status, JobItemsProcessed, TotalJobItems, NumberOfErrors
FROM AsyncApexJob WHERE ID =: batchprocessid ];

188

Batch Apex

Using Batch Apex

For more information about the AsyncApexJob object, see AsyncApexJob in the Object Reference for Salesforce and Force.com.
You can also use this ID with the System.abortJob method.

Batch Apex Examples


The following example uses a Database.QueryLocator:
global class UpdateAccountFields implements Database.Batchable<sObject>{
global final String Query;
global final String Entity;
global final String Field;
global final String Value;
global UpdateAccountFields(String q, String e, String f, String v){
Query=q; Entity=e; Field=f;Value=v;
}
global Database.QueryLocator start(Database.BatchableContext BC){
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC,
List<sObject> scope){
for(Sobject s : scope){s.put(Field,Value);
}
update scope;
}
global void finish(Database.BatchableContext BC){
}
}

The following code can be used to call the above class:


Id batchInstanceId = Database.executeBatch(new UpdateAccountFields(q,e,f,v), 5);

The following class uses batch Apex to reassign all accounts owned by a specific user to a different user.
global class OwnerReassignment implements Database.Batchable<sObject>{
String query;
String email;
Id toUserId;
Id fromUserId;
global Database.querylocator start(Database.BatchableContext BC){
return Database.getQueryLocator(query);}
global void execute(Database.BatchableContext BC, List<sObject> scope){
List<Account> accns = new List<Account>();
for(sObject s : scope){Account a = (Account)s;
if(a.OwnerId==fromUserId){
a.OwnerId=toUserId;
accns.add(a);
}
}
update accns;
}
global void finish(Database.BatchableContext BC){

189

Batch Apex

Using Batch Apex

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();


mail.setToAddresses(new String[] {email});
mail.setReplyTo('[email protected]');
mail.setSenderDisplayName('Batch Processing');
mail.setSubject('Batch Process Completed');
mail.setPlainTextBody('Batch Process has completed');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}

Use the following to execute the OwnerReassignment class in the previous example:
OwnerReassignment reassign = new OwnerReassignment();
reassign.query = 'SELECT Id, Name, Ownerid FROM Account ' +
'WHERE ownerid=\'' + u.id + '\'';
reassign.email='[email protected]';
reassign.fromUserId = u;
reassign.toUserId = u2;
ID batchprocessid = Database.executeBatch(reassign);

The following is an example of a batch Apex class for deleting records.


global class BatchDelete implements Database.Batchable<sObject> {
public String query;
global Database.QueryLocator start(Database.BatchableContext BC){
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<sObject> scope){
delete scope;
DataBase.emptyRecycleBin(scope);
}
global void finish(Database.BatchableContext BC){
}
}

This code calls the BatchDelete batch Apex class to delete old documents. The specified query selects documents to delete
for all documents that are in a specified folder and that are older than a specified date. Next, the sample invokes the batch job.
BatchDelete BDel = new BatchDelete();
Datetime d = Datetime.now();
d = d.addDays(-1);
// Replace this value with the folder ID that contains
// the documents to delete.
String folderId = '00lD000000116lD';
// Query for selecting the documents to delete
BDel.query = 'SELECT Id FROM Document WHERE FolderId=\'' + folderId +
'\' AND CreatedDate < '+d.format('yyyy-MM-dd')+'T'+
d.format('HH:mm')+':00.000Z';
// Invoke the batch job.
ID batchprocessid = Database.executeBatch(BDel);
System.debug('Returned batch process ID: ' + batchProcessId);

190

Batch Apex

Using Batch Apex

Using Callouts in Batch Apex


To use a callout in batch Apex, you must specify Database.AllowsCallouts in the class definition. For example:
global class SearchAndReplace implements Database.Batchable<sObject>,
Database.AllowsCallouts{
}

Callouts include HTTP requests as well as methods defined with the webService keyword.

Using State in Batch Apex


Each execution of a batch Apex job is considered a discrete transaction. For example, a batch Apex job that contains 1,000
records and is executed without the optional scope parameter is considered five transactions of 200 records each.
If you specify Database.Stateful in the class definition, you can maintain state across these transactions. When using
Database.Stateful, only instance member variables retain their values between transactions. Static member variables dont
and are reset between transactions. Maintaining state is useful for counting or summarizing records as they're processed. For
example, suppose your job processed opportunity records. You could define a method in execute to aggregate totals of the
opportunity amounts as they were processed.
If you don't specify Database.Stateful, all static and instance member variables are set back to their original values.
The following example summarizes a custom field total__c as the records are processed:
global class SummarizeAccountTotal implements
Database.Batchable<sObject>, Database.Stateful{
global final String Query;
global integer Summary;
global SummarizeAccountTotal(String q){Query=q;
Summary = 0;
}
global Database.QueryLocator start(Database.BatchableContext BC){
return Database.getQueryLocator(query);
}
global void execute(
Database.BatchableContext BC,
List<sObject> scope){
for(sObject s : scope){
Summary = Integer.valueOf(s.get('total__c'))+Summary;
}
}
global void finish(Database.BatchableContext BC){
}
}

In addition, you can specify a variable to access the initial state of the class. You can use this variable to share the initial state
with all instances of the Database.Batchable methods. For example:
// Implement the interface using a list of Account sObjects
// Note that the initialState variable is declared as final
global class MyBatchable implements Database.Batchable<sObject> {
private final String initialState;
String query;
global MyBatchable(String intialState) {

191

Batch Apex

Using Batch Apex

this.initialState = initialState;
}
global Database.QueryLocator start(Database.BatchableContext BC) {
// Access initialState here
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC,
List<sObject> batch) {
// Access initialState here
}
global void finish(Database.BatchableContext BC) {
// Access initialState here
}
}

Note that initialState is the initial state of the class. You cannot use it to pass information between instances of the class
during execution of the batch job. For example, if you changed the value of initialState in execute, the second chunk
of processed records would not be able to access the new value: only the initial value would be accessible.

Testing Batch Apex


When testing your batch Apex, you can test only one execution of the execute method. You can use the scope parameter
of the executeBatch method to limit the number of records passed into the execute method to ensure that you aren't
running into governor limits.
The executeBatch method starts an asynchronous process. This means that when you test batch Apex, you must make
certain that the batch job is finished before testing against the results. Use the Test methods startTest and stopTest
around the executeBatch method to ensure it finishes before continuing your test. All asynchronous calls made after the
startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously.
If you dont include the executeBatch method within the startTest and stopTest methods, the batch job executes at
the end of your test method for Apex saved using Salesforce.com API version 25.0 and later, but not in earlier versions.
Starting with Apex saved using Salesforce.com API version 22.0, exceptions that occur during the execution of a batch Apex
job that is invoked by a test method are now passed to the calling test method, and as a result, causes the test method to fail.
If you want to handle exceptions in the test method, enclose the code in try and catch statements. You must place the
catch block after the stopTest method. Note however that with Apex saved using Salesforce.com API version 21.0 and
earlier, such exceptions don't get passed to the test method and don't cause test methods to fail.
Note: Asynchronous calls, such as @future or executeBatch, called in a startTest, stopTest block, do not
count against your limits for the number of queued jobs.
The example below tests the OwnerReassignment class.
public static testMethod void testBatch() {
user u = [SELECT ID, UserName FROM User
WHERE username='[email protected]'];
user u2 = [SELECT ID, UserName FROM User
WHERE username='[email protected]'];
String u2id = u2.id;
// Create 200 test accounts - this simulates one execute.
// Important - the Salesforce.com test framework only allows you to
// test one execute.
List <Account> accns = new List<Account>();

192

Batch Apex

Using Batch Apex

for(integer i = 0; i<200; i++){


Account a = new Account(Name='testAccount'+'i',
Ownerid = u.ID);
accns.add(a);
}
insert accns;
Test.StartTest();
OwnerReassignment reassign = new OwnerReassignment();
reassign.query='SELECT ID, Name, Ownerid ' +
'FROM Account ' +
'WHERE OwnerId=\'' + u.Id + '\'' +
' LIMIT 200';
reassign.email='[email protected]';
reassign.fromUserId = u.Id;
reassign.toUserId = u2.Id;
ID batchprocessid = Database.executeBatch(reassign);
Test.StopTest();
System.AssertEquals(
database.countquery('SELECT COUNT()'
+' FROM Account WHERE OwnerId=\'' + u2.Id + '\''),
200);
}
}

Batch Apex Governor Limits


Keep in mind the following governor limits for batch Apex:

Up to five queued or active batch jobs are allowed for Apex.


A user can have up to 50 query cursors open at a time. For example, if 50 cursors are open and a client application still
logged in as the same user attempts to open a new one, the oldest of the 50 cursors is released. Note that this limit is
different for the batch Apex start method, which can have up to five query cursors open at a time per user. The other
batch Apex methods have the higher limit of 50 cursors.
Cursor limits for different Force.com features are tracked separately. For example, you can have 50 Apex query cursors,
50 batch cursors, and 50 Visualforce cursors open at the same time.

A maximum of 50 million records can be returned in the Database.QueryLocator object. If more than 50 million
records are returned, the batch job is immediately terminated and marked as Failed.
The maximum value for the optional scope parameter is 2,000. If set to a higher value, Salesforce chunks the records
returned by the QueryLocator into smaller batches of up to 2,000 records.
If no size is specified with the optional scope parameter, Salesforce chunks the records returned by the QueryLocator
into batches of 200, and then passes each batch to the execute method. Apex governor limits are reset for each execution
of execute.
The start, execute, and finish methods can implement up to 10 callouts each.
Batch executions are limited to 10 callouts per method execution.
The maximum number of batch executions is 250,000 per 24 hours.
Only one batch Apex job's start method can run at a time in an organization. Batch jobs that havent started yet remain
in the queue until they're started. Note that this limit doesnt cause any batch job to fail and execute methods of batch
Apex jobs still run in parallel if more than one job is running.

193

Batch Apex

Understanding Apex Managed Sharing

Batch Apex Best Practices

Use extreme care if you are planning to invoke a batch job from a trigger. You must be able to guarantee that the trigger
will not add more batch jobs than the five that are allowed. In particular, consider API bulk updates, import wizards, mass
record changes through the user interface, and all cases where more than one record can be updated at a time.
When you call Database.executeBatch, Salesforce only places the job in the queue at the scheduled time. Actual
execution may be delayed based on service availability.
When testing your batch Apex, you can test only one execution of the execute method. You can use the scope parameter
of the executeBatch method to limit the number of records passed into the execute method to ensure that you aren't
running into governor limits.
The executeBatch method starts an asynchronous process. This means that when you test batch Apex, you must make
certain that the batch job is finished before testing against the results. Use the Test methods startTest and stopTest
around the executeBatch method to ensure it finishes before continuing your test.
Use Database.Stateful with the class definition if you want to share instance member variables or data across job
transactions. Otherwise, all member variables are reset to their initial state at the start of each transaction.
Methods declared as future aren't allowed in classes that implement the Database.Batchable interface.
Methods declared as future can't be called from a batch Apex class.
You cannot call the Database.executeBatch method from within any batch Apex method.
You cannot use the getContent and getContentAsPDF PageReference methods in a batch job.
In the event of a catastrophic failure such as a service outage, any operations in progress are marked as Failed. You should
run the batch job again to correct any errors.
When a batch Apex job is run, email notifications are sent either to the user who submitted the batch job, or, if the code
is included in a managed package and the subscribing organization is running the batch job, the email is sent to the recipient
listed in the Apex Exception Notification Recipient field.
Each method execution uses the standard governor limits anonymous block, Visualforce controller, or WSDL method.
Each batch Apex invocation creates an AsyncApexJob record. Use the ID of this record to construct a SOQL query to
retrieve the jobs status, number of errors, progress, and submitter. For more information about the AsyncApexJob object,
see AsyncApexJob in the Object Reference for Salesforce and Force.com.
For each 10,000 AsyncApexJob records, Apex creates one additional AsyncApexJob record of type BatchApexWorker
for internal use. When querying for all AsyncApexJob records, we recommend that you filter out records of type
BatchApexWorker using the JobType field. Otherwise, the query will return one more record for every 10,000
AsyncApexJob records. For more information about the AsyncApexJob object, see AsyncApexJob in the Object Reference
for Salesforce and Force.com.
All methods in the class must be defined as global.
For a sharing recalculation, we recommend that the execute method delete and then re-create all Apex managed sharing
for the records in the batch. This ensures the sharing is accurate and complete.

See Also:
Exception Statements
Understanding Execution Governors and Limits
Understanding Sharing

Understanding Apex Managed Sharing


Sharing is the act of granting a user or group of users permission to perform a set of actions on a record or set of records.
Sharing access can be granted using the Salesforce user interface and Force.com, or programmatically using Apex.

194

Batch Apex

Understanding Sharing

This section provides an overview of sharing using Apex:

Understanding Sharing
Sharing a Record Using Apex
Recalculating Apex Managed Sharing

For more information on sharing, see Setting Your Organization-Wide Sharing Defaults in the Salesforce online help.

Understanding Sharing
Sharing enables record-level access control for all custom objects, as well as many standard objects (such as Account, Contact,
Opportunity and Case). Administrators first set an objects organization-wide default sharing access level, and then grant
additional access based on record ownership, the role hierarchy, sharing rules, and manual sharing. Developers can then use
Apex managed sharing to grant additional access programmatically with Apex. Most sharing for a record is maintained in a
related sharing object, similar to an access control list (ACL) found in other platforms.

Types of Sharing
Salesforce has the following types of sharing:
Force.com Managed Sharing
Force.com managed sharing involves sharing access granted by Force.com based on record ownership, the role hierarchy,
and sharing rules:
Record Ownership
Each record is owned by a user or optionally a queue for custom objects, cases and leads. The record owner is
automatically granted Full Access, allowing them to view, edit, transfer, share, and delete the record.
Role Hierarchy
The role hierarchy enables users above another user in the hierarchy to have the same level of access to records
owned by or shared with users below. Consequently, users above a record owner in the role hierarchy are also
implicitly granted Full Access to the record, though this behavior can be disabled for specific custom objects. The
role hierarchy is not maintained with sharing records. Instead, role hierarchy access is derived at runtime. For more
information, see Controlling Access Using Hierarchies in the Salesforce online help.
Sharing Rules
Sharing rules are used by administrators to automatically grant users within a given group or role access to records
owned by a specific group of users. Sharing rules cannot be added to a package and cannot be used to support
sharing logic for apps installed from Force.com AppExchange.
All implicit sharing added by Force.com managed sharing cannot be altered directly using the Salesforce user interface,
SOAP API, or Apex.
User Managed Sharing, also known as Manual Sharing
User managed sharing allows the record owner or any user with Full Access to a record to share the record with a user
or group of users. This is generally done by an end-user, for a single record. Only the record owner and users above the
owner in the role hierarchy are granted Full Access to the record. It is not possible to grant other users Full Access. Users
with the Modify All object-level permission for the given object or the Modify All Data permission can also manually
share a record. User managed sharing is removed when the record owner changes or when the access granted in the
sharing does not grant additional access beyond the object's organization-wide sharing default access level.

195

Batch Apex

Understanding Sharing

Apex Managed Sharing


Apex managed sharing provides developers with the ability to support an applications particular sharing requirements
programmatically through Apex or the SOAP API. This type of sharing is similar to Force.com managed sharing. Only
users with Modify All Data permission can add or change Apex managed sharing on a record. Apex managed sharing
is maintained across record owner changes.
Note: Apex sharing reasons and Apex managed sharing recalculation are only available for custom objects.

The Sharing Reason Field


In the Salesforce user interface, the Reason field on a custom object specifies the type of sharing used for a record. This field
is called rowCause in Apex or the Force.com API.
Each of the following list items is a type of sharing used for records. The tables show Reason field value, and the related
rowCause value.

Force.com Managed Sharing


Reason Field Value

rowCause Value (Used in Apex or the Force.com API)

Account Sharing

ImplicitChild

Associated record owner or sharing

ImplicitParent

Owner

Owner

Sales Team

Team

Sharing Rule

Rule

Territory Assignment Rule

TerritoryRule

User Managed Sharing


Reason Field Value

rowCause Value (Used in Apex or the Force.com API)

Manual Sharing

Manual

Territory Manual

TerritoryManual

Apex Managed Sharing


Reason Field Value

rowCause Value (Used in Apex or the Force.com API)

Defined by developer

Defined by developer

The displayed reason for Apex managed sharing is defined by the developer.

196

Batch Apex

Sharing a Record Using Apex

Access Levels
When determining a users access to a record, the most permissive level of access is used. Most share objects support the
following access levels:
Access Level

API Name

Description

Private

None

Only the record owner and users above the record owner in the role
hierarchy can view and edit the record. This access level only applies to
the AccountShare object.

Read Only

Read

The specified user or group can view the record only.

Read/Write

Edit

The specified user or group can view and edit the record.

Full Access

All

The specified user or group can view, edit, transfer, share, and delete the
record.
Note: This access level can only be granted with Force.com
managed sharing.

Sharing a Record Using Apex


To access sharing programmatically, you must use the share object associated with the standard or custom object for which
you want to share. For example, AccountShare is the sharing object for the Account object, ContactShare is the sharing object
for the Contact object, and so on. In addition, all custom object sharing objects are named as follows, where MyCustomObject
is the name of the custom object:
MyCustomObject__Share

Objects on the detail side of a master-detail relationship do not have an associated sharing object. The detail records access
is determined by the masters sharing object and the relationships sharing setting. For more information, see Custom Object
Security in the Salesforce online help.
A share object includes records supporting all three types of sharing: Force.com managed sharing, user managed sharing, and
Apex managed sharing. Sharing granted to users implicitly through organization-wide defaults, the role hierarchy, and
permissions such as the View All and Modify All permissions for the given object, View All Data, and Modify All Data
are not tracked with this object.
Every share object has the following properties:
Property Name

Description

objectNameAccessLevel

The level of access that the specified user or group has been granted for a share sObject. The
name of the property is AccessLevel appended to the object name. For example, the property
name for LeadShare object is LeadShareAccessLevel. Valid values are:
Edit
Read
All

197

Batch Apex

Sharing a Record Using Apex

Property Name

Description
Note: The All access level can only be used by Force.com managed sharing.

This field must be set to an access level that is higher than the organizations default access
level for the parent object. For more information, see Access Levels on page 197.
ParentID

The ID of the object. This field cannot be updated.

RowCause

The reason why the user or group is being granted access. The reason determines the type of
sharing, which controls who can alter the sharing record. This field cannot be updated.

UserOrGroupId

The user or group IDs to which you are granting access. A group can be a public group, role,
or territory. This field cannot be updated.

You can share a standard or custom object with users or groups. For more information about the types of users and groups
you can share an object with, see User and Group in the Object Reference for Salesforce and Force.com.

Creating User Managed Sharing Using Apex


It is possible to manually share a record to a user or a group using Apex or the SOAP API. If the owner of the record changes,
the sharing is automatically deleted. The following example class contains a method that shares the job specified by the job
ID with the specified user or group ID with read access. It also includes a test method that validates this method. Before you
save this example class, create a custom object called Job.
public class JobSharing {
static boolean manualShareRead(Id recordId, Id userOrGroupId){
// Create new sharing object for the custom object Job.
Job__Share jobShr = new Job__Share();
// Set the ID of record being shared.
jobShr.ParentId = recordId;
// Set the ID of user or group being granted access.
jobShr.UserOrGroupId = userOrGroupId;
// Set the access level.
jobShr.AccessLevel = 'Read';
// Set rowCause to 'manual' for manual sharing.
// This line can be omitted as 'manual' is the default value for sharing objects.
jobShr.RowCause = Schema.Job__Share.RowCause.Manual;
// Insert the sharing record and capture the save result.
// The false parameter allows for partial processing if multiple records passed
// into the operation.
Database.SaveResult sr = Database.insert(jobShr,false);
// Process the save results.
if(sr.isSuccess()){
// Indicates success
return true;
}
else {
// Get first save result error.
Database.Error err = sr.getErrors()[0];

198

Batch Apex

Sharing a Record Using Apex

// Check if the error is related to trival access level.


// Access levels equal or more permissive than the object's default
// access level are not allowed.
// These sharing records are not required and thus an insert exception is acceptable.
if(err.getStatusCode() == StatusCode.FIELD_FILTER_VALIDATION_EXCEPTION
err.getMessage().contains('AccessLevel')){
// Indicates success.
return true;
}
else{
// Indicates failure.
return false;
}

&&

}
}
// Test for the manualShareRead method
static testMethod void testManualShareRead(){
// Select users for the test.
List<User> users = [SELECT Id FROM User WHERE IsActive = true LIMIT 2];
Id User1Id = users[0].Id;
Id User2Id = users[1].Id;
// Create new job.
Job__c j = new Job__c();
j.Name = 'Test Job';
j.OwnerId = user1Id;
insert j;
// Insert manual share for user who is not record owner.
System.assertEquals(manualShareRead(j.Id, user2Id), true);
// Query job sharing records.
List<Job__Share> jShrs = [SELECT Id, UserOrGroupId, AccessLevel,
RowCause FROM job__share WHERE ParentId = :j.Id AND UserOrGroupId= :user2Id];
// Test for only one manual share on job.
System.assertEquals(jShrs.size(), 1, 'Set the object\'s sharing model to Private.');
// Test attributes of manual share.
System.assertEquals(jShrs[0].AccessLevel, 'Read');
System.assertEquals(jShrs[0].RowCause, 'Manual');
System.assertEquals(jShrs[0].UserOrGroupId, user2Id);
// Test invalid job Id.
delete j;
// Insert manual share for deleted job id.
System.assertEquals(manualShareRead(j.Id, user2Id), false);
}
}

Important: The objects organization-wide default access level must not be set to the most permissive access level.
For custom objects, this is Public Read/Write. For more information, see Access Levels on page 197.

Creating Apex Managed Sharing


Apex managed sharing enables developers to programmatically manipulate sharing to support their applications behavior
through Apex or the SOAP API. This type of sharing is similar to Force.com managed sharing. Only users with Modify All
Data permission can add or change Apex managed sharing on a record. Apex managed sharing is maintained across record
owner changes.

199

Batch Apex

Sharing a Record Using Apex

Apex managed sharing must use an Apex sharing reason. Apex sharing reasons are a way for developers to track why they shared
a record with a user or group of users. Using multiple Apex sharing reasons simplifies the coding required to make updates
and deletions of sharing records. They also enable developers to share with the same user or group multiple times using different
reasons.
Apex sharing reasons are defined on an object's detail page. Each Apex sharing reason has a label and a name:
The label displays in the Reason column when viewing the sharing for a record in the user interface. This allows users
and administrators to understand the source of the sharing. The label is also enabled for translation through the Translation
Workbench.
The name is used when referencing the reason in the API and Apex.

All Apex sharing reason names have the following format:


MyReasonName__c

Apex sharing reasons can be referenced programmatically as follows:


Schema.CustomObject__Share.rowCause.SharingReason__c

For example, an Apex sharing reason called Recruiter for an object called Job can be referenced as follows:
Schema.Job__Share.rowCause.Recruiter__c

For more information, see Schema Methods on page 324.


To create an Apex sharing reason:
1.
2.
3.
4.

Click Your Name > Setup > Create > Objects.


Select the custom object.
Click New in the Apex Sharing Reasons related list.
Enter a label for the Apex sharing reason. The label displays in the Reason column when viewing the sharing for a record
in the user interface. The label is also enabled for translation through the Translation Workbench.
5. Enter a name for the Apex sharing reason. The name is used when referencing the reason in the API and Apex. This name
can contain only underscores and alphanumeric characters, and must be unique in your organization. It must begin with
a letter, not include spaces, not end with an underscore, and not contain two consecutive underscores.
6. Click Save.
Note: Apex sharing reasons and Apex managed sharing recalculation are only available for custom objects.

Apex Managed Sharing Example


For this example, suppose that you are building a recruiting application and have an object called Job. You want to validate
that the recruiter and hiring manager listed on the job have access to the record. The following trigger grants the recruiter and
hiring manager access when the job record is created. This example requires a custom object called Job with two lookup fields
that are associated with User records and are called Hiring_Manager and Recruiter. Also, the Job custom object should have
two sharing reasons added called Hiring_Manager and Recruiter.
trigger JobApexSharing on Job__c (after insert) {
if(trigger.isInsert){
// Create a new list of sharing objects for Job
List<Job__Share> jobShrs = new List<Job__Share>();

200

Batch Apex

Sharing a Record Using Apex

// Declare variables for recruiting and hiring manager sharing


Job__Share recruiterShr;
Job__Share hmShr;
for(Job__c job : trigger.new){
// Instantiate the sharing objects
recruiterShr = new Job__Share();
hmShr = new Job__Share();
// Set the ID of record being shared
recruiterShr.ParentId = job.Id;
hmShr.ParentId = job.Id;
// Set the ID of user or group being granted access
recruiterShr.UserOrGroupId = job.Recruiter__c;
hmShr.UserOrGroupId = job.Hiring_Manager__c;
// Set the access level
recruiterShr.AccessLevel = 'edit';
hmShr.AccessLevel = 'read';
// Set the Apex sharing reason for hiring manager and recruiter
recruiterShr.RowCause = Schema.Job__Share.RowCause.Recruiter__c;
hmShr.RowCause = Schema.Job__Share.RowCause.Hiring_Manager__c;
// Add objects to list for insert
jobShrs.add(recruiterShr);
jobShrs.add(hmShr);
}
// Insert sharing records and capture save result
// The false parameter allows for partial processing if multiple records are passed
// into the operation
Database.SaveResult[] lsr = Database.insert(jobShrs,false);
// Create counter
Integer i=0;
// Process the save results
for(Database.SaveResult sr : lsr){
if(!sr.isSuccess()){
// Get the first save result error
Database.Error err = sr.getErrors()[0];
// Check if the error is related to a trivial access level
// Access levels equal or more permissive than the object's default
// access level are not allowed.
// These sharing records are not required and thus an insert exception is
// acceptable.
if(!(err.getStatusCode() == StatusCode.FIELD_FILTER_VALIDATION_EXCEPTION
&& err.getMessage().contains('AccessLevel'))){
// Throw an error when the error is not related to trivial access level.
trigger.newMap.get(jobShrs[i].ParentId).
addError(
'Unable to grant sharing access due to following exception: '
+ err.getMessage());
}
}
i++;
}
}
}

201

Batch Apex

Recalculating Apex Managed Sharing

Under certain circumstances, inserting a share row results in an update of an existing share row. Consider these examples:

If a manual share access level is set to Read and you insert a new one thats set to Write, the original share rows are updated
to Write, indicating the higher level of access.
If users can access an account because they can access its child records (contact, case, opportunity, and so on), and an
account sharing rule is created, the row cause of the parent implicit share is replaced by the sharing rule row cause, indicating
the higher level of access.
Important: The objects organization-wide default access level must not be set to the most permissive access level.
For custom objects, this is Public Read/Write. For more information, see Access Levels on page 197.

Recalculating Apex Managed Sharing


Salesforce automatically recalculates sharing for all records on an object when its organization-wide sharing default access level
is changed. The recalculation adds Force.com managed sharing when appropriate. In addition, all types of sharing are removed
if the access they grant is considered redundant. For example, manual sharing which grants Read Only access to a user is
deleted when the objects sharing model is changed from Private to Public Read Only.
To recalculate Apex managed sharing, you must write an Apex class that implements a Salesforce-provided interface to do
the recalculation. You must then associate the class with the custom object, on the custom object's detail page, in the Apex
Sharing Recalculation related list.
Note: Apex sharing reasons and Apex managed sharing recalculation are only available for custom objects.

You can execute this class from the custom object detail page where the Apex sharing reason is specified. An administrator
might need to recalculate the Apex managed sharing for an object if a locking issue prevented Apex code from granting access
to a user as defined by the applications logic. You can also use the Database.executeBatch method to programmatically
invoke an Apex managed sharing recalculation.
Note: Every time a custom object's organization-wide sharing default access level is updated, any Apex recalculation
classes defined for associated custom object are also executed.
To monitor or stop the execution of the Apex recalculation, click Your Name > Setup > Monitoring > Apex Jobs. For more
information, see Monitoring the Apex Job Queue in the Salesforce online help.

Creating an Apex Class for Recalculating Sharing


To recalculate Apex managed sharing, you must write an Apex class to do the recalculation. This class must implement the
Salesforce-provided interface Database.Batchable.
The Database.Batchable interface is used for all batch Apex processes, including recalculating Apex managed sharing.
You can implement this interface more than once in your organization. For more information on the methods that must be
implemented, see Using Batch Apex on page 186.
Before creating an Apex managed sharing recalculation class, also consider the best practices.
Important: The objects organization-wide default access level must not be set to the most permissive access level.
For custom objects, this is Public Read/Write. For more information, see Access Levels on page 197.

202

Batch Apex

Recalculating Apex Managed Sharing

Apex Managed Sharing Recalculation Example


For this example, suppose that you are building a recruiting application and have an object called Job. You want to validate
that the recruiter and hiring manager listed on the job have access to the record. The following Apex class performs this
validation. This example requires a custom object called Job with two lookup fields that are associated with User records and
are called Hiring_Manager and Recruiter. Also, the Job custom object should have two sharing reasons added called
Hiring_Manager and Recruiter. Before you run this sample, replace the email address with a valid email address that is used
to send error notifications and job completion notifications to.
global class JobSharingRecalc implements Database.Batchable<sObject> {
// String to hold email address that emails will be sent to.
// Replace its value with a valid email address.
static String emailAddress = '[email protected]';
// The start method is called at the beginning of a sharing recalculation.
// This method returns a SOQL query locator containing the records to be recalculated.
// This method must be global.
global Database.QueryLocator start(Database.BatchableContext BC){
return Database.getQueryLocator([SELECT Id, Hiring_Manager__c, Recruiter__c
FROM Job__c]);
}
// The executeBatch method is called for each chunk of records returned from start.
// This method must be global.
global void execute(Database.BatchableContext BC, List<sObject> scope){
// Create a map for the chunk of records passed into method.
Map<ID, Job__c> jobMap = new Map<ID, Job__c>((List<Job__c>)scope);
// Create a list of Job__Share objects to be inserted.
List<Job__Share> newJobShrs = new List<Job__Share>();
// Locate all existing sharing records for the Job records in the batch.
// Only records using an Apex sharing reason for this app should be returned.
List<Job__Share> oldJobShrs = [SELECT Id FROM Job__Share WHERE Id IN
:jobMap.keySet() AND
(RowCause = :Schema.Job__Share.rowCause.Recruiter__c OR
RowCause = :Schema.Job__Share.rowCause.Hiring_Manager__c)];
// Construct new sharing records for the hiring manager and recruiter
// on each Job record.
for(Job__c job : jobMap.values()){
Job__Share jobHMShr = new Job__Share();
Job__Share jobRecShr = new Job__Share();
// Set the ID of user (hiring manager) on the Job record being granted access.
jobHMShr.UserOrGroupId = job.Hiring_Manager__c;
// The hiring manager on the job should always have 'Read Only' access.
jobHMShr.AccessLevel = 'Read';
// The ID of the record being shared
jobHMShr.ParentId = job.Id;
// Set the rowCause to the Apex sharing reason for hiring manager.
// This establishes the sharing record as Apex managed sharing.
jobHMShr.RowCause = Schema.Job__Share.RowCause.Hiring_Manager__c;
// Add sharing record to list for insertion.
newJobShrs.add(jobHMShr);
// Set the ID of user (recruiter) on the Job record being granted access.
jobRecShr.UserOrGroupId = job.Recruiter__c;

203

Batch Apex

Recalculating Apex Managed Sharing

// The recruiter on the job should always have 'Read/Write' access.


jobRecShr.AccessLevel = 'Edit';
// The ID of the record being shared
jobRecShr.ParentId = job.Id;
// Set the rowCause to the Apex sharing reason for recruiter.
// This establishes the sharing record as Apex managed sharing.
jobRecShr.RowCause = Schema.Job__Share.RowCause.Recruiter__c;
// Add the sharing record to the list for insertion.
newJobShrs.add(jobRecShr);
}
try {
// Delete the existing sharing records.
// This allows new sharing records to be written from scratch.
Delete oldJobShrs;
// Insert the new sharing records and capture the save result.
// The false parameter allows for partial processing if multiple records are
// passed into operation.
Database.SaveResult[] lsr = Database.insert(newJobShrs,false);
// Process the save results for insert.
for(Database.SaveResult sr : lsr){
if(!sr.isSuccess()){
// Get the first save result error.
Database.Error err = sr.getErrors()[0];
// Check if the error is related to trivial access level.
// Access levels equal or more permissive than the object's default
// access level are not allowed.
// These sharing records are not required and thus an insert exception
// is acceptable.
if(!(err.getStatusCode() == StatusCode.FIELD_FILTER_VALIDATION_EXCEPTION
&& err.getMessage().contains('AccessLevel'))){
// Error is not related to trivial access level.
// Send an email to the Apex job's submitter.
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {emailAddress};
mail.setToAddresses(toAddresses);
mail.setSubject('Apex Sharing Recalculation Exception');
mail.setPlainTextBody(
'The Apex sharing recalculation threw the following exception: ' +
err.getMessage());
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}
}
} catch(DmlException e) {
// Send an email to the Apex job's submitter on failure.
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {emailAddress};
mail.setToAddresses(toAddresses);
mail.setSubject('Apex Sharing Recalculation Exception');
mail.setPlainTextBody(
'The Apex sharing recalculation threw the following exception: ' +
e.getMessage());
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}
// The finish method is called at the end of a sharing recalculation.
// This method must be global.

204

Batch Apex

Recalculating Apex Managed Sharing

global void finish(Database.BatchableContext BC){


// Send an email to the Apex job's submitter notifying of job completion.
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {emailAddress};
mail.setToAddresses(toAddresses);
mail.setSubject('Apex Sharing Recalculation Completed.');
mail.setPlainTextBody
('The Apex sharing recalculation finished processing');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}

Testing Apex Managed Sharing Recalculations


This example inserts five Job records and invokes the batch job that is implemented in the batch class of the previous example.
This example requires a custom object called Job with two lookup fields that are associated with User records and are called
Hiring_Manager and Recruiter. Also, the Job custom object should have two sharing reasons added called Hiring_Manager
and Recruiter. Before you run this test, set the organization-wide default sharing for Job to Private. Note that since email
messages arent sent from tests, and because the batch class is invoked by a test method, the email notifications wont be sent
in this case.
@isTest
private class JobSharingTester {
// Test for the JobSharingRecalc class
static testMethod void testApexSharing(){
// Instantiate the class implementing the Database.Batchable interface.
JobSharingRecalc recalc = new JobSharingRecalc();
// Select users for the test.
List<User> users = [SELECT Id FROM User WHERE IsActive = true LIMIT 2];
ID User1Id = users[0].Id;
ID User2Id = users[1].Id;
// Insert some test job records.
List<Job__c> testJobs = new List<Job__c>();
for (Integer i=0;i<5;i++) {
Job__c j = new Job__c();
j.Name = 'Test Job ' + i;
j.Recruiter__c = User1Id;
j.Hiring_Manager__c = User2Id;
testJobs.add(j);
}
insert testJobs;
Test.startTest();
// Invoke the Batch class.
String jobId = Database.executeBatch(recalc);
Test.stopTest();
// Get the Apex job and verify there are no errors.
AsyncApexJob aaj = [Select JobType, TotalJobItems, JobItemsProcessed, Status,
CompletedDate, CreatedDate, NumberOfErrors
from AsyncApexJob where Id = :jobId];
System.assertEquals(0, aaj.NumberOfErrors);
// This query returns jobs and related sharing records that were inserted
// by the batch job's execute method.
List<Job__c> jobs = [SELECT Id, Hiring_Manager__c, Recruiter__c,
(SELECT Id, ParentId, UserOrGroupId, AccessLevel, RowCause FROM Shares
WHERE (RowCause = :Schema.Job__Share.rowCause.Recruiter__c OR

205

Batch Apex

Recalculating Apex Managed Sharing

RowCause = :Schema.Job__Share.rowCause.Hiring_Manager__c))
FROM Job__c];
// Validate that Apex managed sharing exists on jobs.
for(Job__c job : jobs){
// Two Apex managed sharing records should exist for each job
// when using the Private org-wide default.
System.assert(job.Shares.size() == 2);
for(Job__Share jobShr : job.Shares){
// Test the sharing record for hiring manager on job.
if(jobShr.RowCause == Schema.Job__Share.RowCause.Hiring_Manager__c){
System.assertEquals(jobShr.UserOrGroupId,job.Hiring_Manager__c);
System.assertEquals(jobShr.AccessLevel,'Read');
}
// Test the sharing record for recruiter on job.
else if(jobShr.RowCause == Schema.Job__Share.RowCause.Recruiter__c){
System.assertEquals(jobShr.UserOrGroupId,job.Recruiter__c);
System.assertEquals(jobShr.AccessLevel,'Edit');
}
}
}
}
}

Associating an Apex Class Used for Recalculation


An Apex class used for recalculation must be associated with a custom object.
To associate an Apex managed sharing recalculation class with a custom object:
1.
2.
3.
4.

Click Your Name > Setup > Create > Objects.


Select the custom object.
Click New in the Apex Sharing Recalculations related list.
Choose the Apex class that recalculates the Apex sharing for this object. The class you choose must implement the
Database.Batchable interface. You cannot associate the same Apex class multiple times with the same custom object.
5. Click Save.

206

Chapter 8
Debugging Apex
In this chapter ...

Understanding the Debug Log


Handling Uncaught Exceptions
Understanding Execution Governors
and Limits
Using Governor Limit Email
Warnings

Apex provides debugging support. You can debug your Apex code using the
Developer Console and debug logs. To further aid debugging, Apex sends emails
to developers for unhandled exceptions. Furthermore, Apex enforces a certain
set of governor limits for your running code to ensure shared resources arent
monopolized in a multi-tenant environment. Last but not least, you can select
to have emails sent to end-users who are running code that surpasses a certain
percentage of any governor limit.
This chapter covers the following:

Understanding the Debug Log


Handling Uncaught Exceptions
Understanding Execution Governors and Limits
Using Governor Limit Email Warnings

207

Debugging Apex

Understanding the Debug Log

Understanding the Debug Log


A debug log records database operations, system processes, and errors that occur when executing a transaction or while running
unit tests. The system generates a debug log for a user every time that user executes a transaction that is included in the filter
criteria.
You can retain and manage the debug logs for specific users.
To view saved debug logs, click Your Name > Setup > Monitoring > Debug Logs.
The following are the limits for debug logs:

Once a user is added, that user can record up to 20 debug logs. After a user reaches this limit, debug logs stop being recorded
for that user. Click Reset on the Monitoring Debug logs page to reset the number of logs for that user back to 20. Any
existing logs are not overwritten.
Each debug log can only be 2 MB. Debug logs that are larger than 2 MB in size are truncated.
Each organization can retain up to 50 MB of debug logs. Once your organization has reached 50 MB of debug logs, the
oldest debug logs start being overwritten.

Inspecting the Debug Log Sections


After you generate a debug log, the type and amount of information listed depends on the filter values you set for the user.
However, the format for a debug log is always the same.
A debug log has the following sections:
Header
The header contains the following information:

The version of the API used during the transaction.


The log category and level used to generate the log. For example:

The following is an example of a header:


25.0
APEX_CODE,DEBUG;APEX_PROFILING,INFO;CALLOUT,INFO;DB,INFO;SYSTEM,DEBUG;VALIDATION,INFO;VISUALFORCE,INFO;
WORKFLOW,INFO

In this example, the API version is 25.0, and the following debug log categories and levels have been set:
Apex Code

DEBUG

Apex Profiling

INFO

Callout

INFO

Database

INFO

System

DEBUG

Validation

INFO

Visualforce

INFO

Workflow

INFO

208

Debugging Apex

Understanding the Debug Log

Execution Units
An execution unit is equivalent to a transaction. It contains everything that occurred within the transaction. The execution
is delimited by EXECUTION_STARTED and EXECUTION_FINISHED.
Code Units
A code unit is a discrete unit of work within a transaction. For example, a trigger is one unit of code, as is a webService
method, or a validation rule.
Note: A class is not a discrete unit of code.

Units of code are indicated by CODE_UNIT_STARTED and CODE_UNIT_FINISHED. Units of work can embed other
units of work. For example:
EXECUTION_STARTED
CODE_UNIT_STARTED|[EXTERNAL]execute_anonymous_apex
CODE_UNIT_STARTED|[EXTERNAL]MyTrigger on Account trigger event BeforeInsert for [new]
CODE_UNIT_FINISHED <-- The trigger ends
CODE_UNIT_FINISHED <-- The executeAnonymous ends
EXECUTION_FINISHED

Units of code include, but are not limited to, the following:

Triggers
Workflow invocations and time-based workflow
Validation rules
Approval processes
Apex lead convert
@future method invocations
Web service invocations
executeAnonymous calls
Visualforce property accesses on Apex controllers
Visualforce actions on Apex controllers
Execution of the batch Apex start and finish methods, as well as each execution of the execute method
Execution of the Apex System.Schedule execute method
Incoming email handling

Log Lines
Included inside the units of code. These indicate what code or rules are being executed, or messages being specifically
written to the debug log. For example:

Figure 5: Debug Log Line Example

209

Debugging Apex

Understanding the Debug Log

Log lines are made up of a set of fields, delimited by a pipe (|). The format is:

timestamp: consists of the time when the event occurred and a value between parentheses. The time is in the user's
time zone and in the format HH:mm:ss.SSS. The value represents the time elapsed in nanoseconds since the start
of the request. The elapsed time value is excluded from logs reviewed in the Developer Console.
event identifier: consists of the specific event that triggered the debug log being written to, such as SAVEPOINT_RESET
or VALIDATION_RULE, and any additional information logged with that event, such as the method name or the line
and character number where the code was executed.

Additional Log Data


In addition, the log contains the following information:

Cumulative resource usageLogged at the end of many code units, such as triggers, executeAnonymous, batch
Apex message processing, @future methods, Apex test methods, Apex web service methods, and Apex lead convert.
Cumulative profiling informationLogged once at the end of the transaction. Contains information about the most
expensive queries (that used the most resources), DML invocations, and so on.

The following is an example debug log:


22.0
APEX_CODE,DEBUG;APEX_PROFILING,INFO;CALLOUT,INFO;DB,INFO;SYSTEM,DEBUG;VALIDATION,INFO;VISUALFORCE,INFO;
WORKFLOW,INFO
11:47:46.030 (30064000)|EXECUTION_STARTED
11:47:46.030 (30159000)|CODE_UNIT_STARTED|[EXTERNAL]|TRIGGERS
11:47:46.030 (30271000)|CODE_UNIT_STARTED|[EXTERNAL]|01qD00000004JvP|myAccountTrigger on
Account trigger event BeforeUpdate for [001D000000IzMaE]
11:47:46.038 (38296000)|SYSTEM_METHOD_ENTRY|[2]|System.debug(ANY)
11:47:46.038 (38450000)|USER_DEBUG|[2]|DEBUG|Hello World!
11:47:46.038 (38520000)|SYSTEM_METHOD_EXIT|[2]|System.debug(ANY)
11:47:46.546 (38587000)|CUMULATIVE_LIMIT_USAGE
11:47:46.546|LIMIT_USAGE_FOR_NS|(default)|
Number of SOQL queries: 0 out of 100
Number of query rows: 0 out of 50000
Number of SOSL queries: 0 out of 20
Number of DML statements: 0 out of 150
Number of DML rows: 0 out of 10000
Number of script statements: 1 out of 200000
Maximum heap size: 0 out of 6000000
Number of callouts: 0 out of 10
Number of Email Invocations: 0 out of 10
Number of fields describes: 0 out of 100
Number of record type describes: 0 out of 100
Number of child relationships describes: 0 out of 100
Number of picklist describes: 0 out of 100
Number of future calls: 0 out of 10
11:47:46.546|CUMULATIVE_LIMIT_USAGE_END
11:47:46.038
BeforeUpdate
11:47:47.154
11:47:47.154

(38715000)|CODE_UNIT_FINISHED|myAccountTrigger on Account trigger event


for [001D000000IzMaE]
(1154831000)|CODE_UNIT_FINISHED|TRIGGERS
(1154881000)|EXECUTION_FINISHED

Setting Debug Log Filters for Apex Classes and Triggers


Debug log filtering provides a mechanism for fine-tuning the log verbosity at the trigger and class level. This is especially
helpful when debugging Apex logic. For example, to evaluate the output of a complex process, you can raise the log verbosity
for a given class while turning off logging for other classes or triggers within a single request.

210

Debugging Apex

Understanding the Debug Log

When you override the debug log levels for a class or trigger, these debug levels also apply to the class methods that your class
or trigger calls and the triggers that get executed as a result. All class methods and triggers in the execution path inherit the
debug log settings from their caller, unless they have these settings overridden.
The following diagram illustrates overriding debug log levels at the class and trigger level. For this scenario, suppose Class1
is causing some issues that you would like to take a closer look at. To this end, the debug log levels of Class1 are raised to
the finest granularity. Class3 doesn't override these log levels, and therefore inherits the granular log filters of Class1.
However, UtilityClass has already been tested and is known to work properly, so it has its log filters turned off. Similarly,
Class2 isn't in the code path that causes a problem, therefore it has its logging minimized to log only errors for the Apex
Code category. Trigger2 inherits these log settings from Class2.

Figure 6: Fine-tuning debug logging for classes and triggers


The following is a pseudo-code example that the diagram is based on.
1. Trigger1 calls a method of Class1 and another method of Class2. For example:
trigger Trigger1 on Account (before insert) {
Class1.someMethod();
Class2.anotherMethod();
}

2. Class1 calls a method of Class3, which in turn calls a method of a utility class. For example:
public class Class1 {
public static void someMethod() {
Class3.thirdMethod();
}
}
public class Class3 {
public static void thirdMethod() {
UtilityClass.doSomething();
}
}

3. Class2 causes a trigger, Trigger2, to be executed. For example:


public class Class2 {
public static void anotherMethod() {
// Some code that causes Trigger2 to be fired.
}
}

211

Debugging Apex

Using the Developer Console

To set log filters:


1. From a class or trigger detail page, click Log Filters.
2. Click Override Log Filters.
The log filters are set to the default log levels.
3. Choose the log level desired for each log category.
To learn more about debug log categories, debug log levels, and debug log events, see Setting Debug Log Filters.

See Also:
Using the Developer Console
Debugging Apex API Calls

Using the Developer Console


The Developer Console is a collection of tools you can use to analyze and troubleshoot applications in your Salesforce
organization. Its a popup window composed of a set of related tools that allow you to access your source code and review how
it executes. It can also be used to monitor database events, workflows, callouts, validation logic, cumulative resources used
versus system limits, and other events that are recorded in debug logs. Its a context-sensitive execution viewer, showing the
source of an operation, what triggered that operation, and what occurred afterward.

Figure 7: The Developer Console:


To learn about the Developer Console tools, see Navigating within the Developer Console in the online help in the
Salesforce online help.
To learn about the different sections of the Developer Console System Log, see The System Log View in the Salesforce
online help.

212

Debugging Apex

Using the Developer Console

To learn more about some typical ways you might use the Developer Console, for example, evaluating Visualforce pages,
tracking DML in your transaction or monitoring performance, see Examples of Using the Developer Console in the Salesforce
online help.
When using the Developer Console or monitoring a debug log, you can specify the level of information that gets included in
the log.
Log category
The type of information logged, such as information from Apex or workflow rules.
Log level
The amount of information logged.
Event type
The combination of log category and log level that specify which events get logged. Each event can log additional
information, such as the line and character number where the event started, fields associated with the event, duration of
the event in milliseconds, and so on.

Debug Log Categories


You can specify the following log categories. The amount of information logged for each category depends on the log level:
Log Category

Description

Database

Includes information about database activity, including every data manipulation


language (DML) statement or inline SOQL or SOSL query.

Workflow

Includes information for workflow rules, such as the rule name, the actions taken, and
so on.

Validation

Includes information about validation rules, such as the name of the rule, whether the
rule evaluated true or false, and so on.

Callout

Includes the request-response XML that the server is sending and receiving from an
external Web service. This is useful when debugging issues related to using Force.com
Web services API calls.

Apex Code

Includes information about Apex code and can include information such as log
messages generated by DML statements, inline SOQL or SOSL queries, the start
and completion of any triggers, and the start and completion of any test method, and
so on.

Apex Profiling

Includes cumulative profiling information, such as the limits for your namespace, the
number of emails sent, and so on.

Visualforce

Includes information about Visualforce events including serialization and deserialization


of the view state or the evaluation of a formula field in a Visualforce page.

System

Includes information about calls to all system methods such as the System.debug
method.

Debug Log Levels


You can specify the following log levels. The levels are listed from lowest to highest. Specific events are logged based on the
combination of category and levels. Most events start being logged at the INFO level. The level is cumulative, that is, if you
select FINE, the log will also include all events logged at DEBUG, INFO, WARN and ERROR levels.

213

Debugging Apex

Using the Developer Console

Note: Not all levels are available for all categories: only the levels that correspond to one or more events.

ERROR
WARN
INFO
DEBUG
FINE
FINER
FINEST

Debug Event Types


The following is an example of what is written to the debug log. The event is USER_DEBUG. The format is timestamp |
event identifier:

timestamp: consists of the time when the event occurred and a value between parentheses. The time is in the user's time
zone and in the format HH:mm:ss.SSS. The value represents the time elapsed in nanoseconds since the start of the request.
The elapsed time value is excluded from logs reviewed in the Developer Console.
event identifier: consists of the specific event that triggered the debug log being written to, such as SAVEPOINT_RESET or
VALIDATION_RULE, and any additional information logged with that event, such as the method name or the line and
character number where the code was executed.

The following is an example of a debug log line.

Figure 8: Debug Log Line Example


In this example, the event identifier is made up of the following:

Event name:
USER_DEBUG

Line number of the event in the code:


[2]

Logging level the System.Debug method was set to:


DEBUG

User-supplied string for the System.Debug method:


Hello world!

214

Debugging Apex

Using the Developer Console

The following example of a log line is triggered by this code snippet.

Figure 9: Debug Log Line Code Snippet


The following log line is recorded when the test reaches line 5 in the code:
15:51:01.071 (55856000)|DML_BEGIN|[5]|Op:Insert|Type:Invoice_Statement__c|Rows:1

In this example, the event identifier is made up of the following:

Event name:
DML_BEGIN

Line number of the event in the code:


[5]

DML operation typeInsert:


Op:Insert

Object name:
Type:Invoice_Statement__c

Number of rows passed into the DML operation:


Rows:1

The following table lists the event types that are logged, what fields or other information get logged with each event, as well
as what combination of log level and category cause an event to be logged.
Event Name

Fields or Information Logged With Event Category Logged

Level Logged

BULK_HEAP_ALLOCATE

Number of bytes allocated

Apex Code

FINEST

CALLOUT_REQUEST

Line number, request headers

Callout

INFO and above

CALLOUT_RESPONSE

Line number, response body

Callout

INFO and above

CODE_UNIT_FINISHED

None

Apex Code

ERROR and above

CODE_UNIT_STARTED

Line number, code unit name, such as

Apex Code

ERROR and above

MyTrigger on Account trigger


event BeforeInsert for [new]

215

Debugging Apex

Using the Developer Console

Event Name

Fields or Information Logged With Event Category Logged

Level Logged

CONSTRUCTOR_ENTRY

Line number, Apex class ID, the sring


<init>() with the types of parameters, if
any, between the parentheses

Apex Code

DEBUG and above

CONSTRUCTOR_EXIT

Line number, the string <init>() with the Apex Code


types of parameters, if any, between the
parentheses

DEBUG and above

CUMULATIVE_LIMIT_USAGE

None

Apex Profiling

INFO and above

CUMULATIVE_LIMIT_USAGE_END None

Apex Profiling

INFO and above

None

Apex Profiling

FINE and above

CUMULATIVE_PROFILING_BEGIN None

Apex Profiling

FINE and above

CUMULATIVE_PROFILING_END None

Apex Profiling

FINE and above

CUMULATIVE_PROFILING

DML_BEGIN

Line number, operation (such as Insert, Apex Code


Update, and so on), record name or type,
number of rows passed into DML operation

INFO and above

DML_END

Line number

Apex Code

INFO and above

EMAIL_QUEUE

Line number

Apex Code

INFO and above

ENTERING_MANAGED_PKG

Package namespace

Apex Code

INFO and above

EXCEPTION_THROWN

Line number, exception type, message

Apex Code

INFO and above

EXECUTION_FINISHED

None

Apex Code

ERROR and above

EXECUTION_STARTED

None

Apex Code

ERROR and above

FATAL_ERROR

Exception type, message, stack trace

Apex Code

ERROR and above

HEAP_ALLOCATE

Line number, number of bytes

Apex Code

FINER and above

HEAP_DEALLOCATE

Line number, number of bytes deallocated

Apex Code

FINER and above

IDEAS_QUERY_EXECUTE

Line number

DB

FINEST

LIMIT_USAGE_FOR_NS

Namespace, following limits:

Apex Profiling

FINEST

Number of SOQL queries


Number of query rows
Number of SOSL queries
Number of DML statements
Number of DML rows
Number of code statements
Maximum heap size
Number of callouts
Number of Email Invocations
Number of fields describes

216

Debugging Apex

Event Name

Using the Developer Console

Fields or Information Logged With Event Category Logged

Level Logged

Number of record type describes


Number of child relationships
describes
Number of picklist describes
Number of future calls
Number of find similar calls
Number of System.runAs()
invocations

METHOD_ENTRY

Line number, the Force.com ID of the class, Apex Code


method signature

DEBUG and above

METHOD_EXIT

Line number, the Force.com ID of the class, Apex Code


method signature.

DEBUG and above

For constructors, the following information


is logged: Line number, class name.
POP_TRACE_FLAGS

Line number, the Force.com ID of the class System


or trigger that has its log filters set and that
is going into scope, the name of this class or
trigger, the log filter settings that are now in
effect after leaving this scope

INFO and above

PUSH_TRACE_FLAGS

Line number, the Force.com ID of the class System


or trigger that has its log filters set and that
is going out of scope, the name of this class
or trigger, the log filter settings that are now
in effect after entering this scope

INFO and above

QUERY_MORE_ITERATIONS

Line number, number of queryMore


iterations

DB

INFO and above

SAVEPOINT_ROLLBACK

Line number, Savepoint name

DB

INFO and above

SAVEPOINT_SET

Line number, Savepoint name

DB

INFO and above

SLA_END

Number of cases, load time, processing time, Workflow


number of case milestones to
insert/update/delete, new trigger

INFO and above

SLA_EVAL_MILESTONE

Milestone ID

Workflow

INFO and above

SLA_NULL_START_DATE

None

Workflow

INFO and above

SLA_PROCESS_CASE

Case ID

Workflow

INFO and above

SOQL_EXECUTE_BEGIN

Line number, number of aggregations, query DB


source

INFO and above

217

Debugging Apex

Using the Developer Console

Event Name

Fields or Information Logged With Event Category Logged

Level Logged

SOQL_EXECUTE_END

Line number, number of rows, duration in


milliseconds

DB

INFO and above

SOSL_EXECUTE_BEGIN

Line number, query source

DB

INFO and above

SOSL_EXECUTE_END

Line number, number of rows, duration in


milliseconds

DB

INFO and above

Apex Profiling

FINE and above

Apex Code

FINER and above

STACK_FRAME_VARIABLE_LIST Frame number, variable list of the form:


Variable number | Value. For example:
var1:50
var2:'Hello World'

STATEMENT_EXECUTE

Line number

STATIC_VARIABLE_LIST

Variable list of the form: Variable number Apex Profiling


| Value. For example:

FINE and above

var1:50
var2:'Hello World'

SYSTEM_CONSTRUCTOR_ENTRY Line number, the string <init>() with the System

DEBUG

types of parameters, if any, between the


parentheses
SYSTEM_CONSTRUCTOR_EXIT

Line number, the string <init>() with the System


types of parameters, if any, between the
parentheses

DEBUG

SYSTEM_METHOD_ENTRY

Line number, method signature

System

DEBUG

SYSTEM_METHOD_EXIT

Line number, method signature

System

DEBUG

SYSTEM_MODE_ENTER

Mode name

System

INFO and above

SYSTEM_MODE_EXIT

Mode name

System

INFO and above

TESTING_LIMITS

None

Apex Profiling

INFO and above

Apex Profiling

FINE and above

Apex Code

DEBUG and above


by default. If the
user sets the log
level for the

TOTAL_EMAIL_RECIPIENTS_QUEUED Number of emails sent


USER_DEBUG

Line number, logging level, user-supplied


string

System.Debug

method, the event is


logged at that level
instead.
VALIDATION_ERROR

Error message

Validation

INFO and above

VALIDATION_FAIL

None

Validation

INFO and above

218

Debugging Apex

Using the Developer Console

Event Name

Fields or Information Logged With Event Category Logged

Level Logged

VALIDATION_FORMULA

Formula source, values

Validation

INFO and above

VALIDATION_PASS

None

Validation

INFO and above

VALIDATION_RULE

Rule name

Validation

INFO and above

VARIABLE_ASSIGNMENT

Line number, variable name, a string


representation of the variable's value, the
variable's address

Apex Code

FINEST

VARIABLE_SCOPE_BEGIN

Line number, variable name, type, a value


Apex Code
that indicates if the variable can be referenced,
a value that indicates if the variable is static

FINEST

VARIABLE_SCOPE_END

None

Apex Code

FINEST

VF_APEX_CALL

Element name, method name, return type

Apex Code

INFO and above

VF_DESERIALIZE_VIEWSTATE_BEGIN View state ID

Visualforce

INFO and above

VF_DESERIALIZE_VIEWSTATE_END None

Visualforce

INFO and above

VF_EVALUATE_FORMULA_BEGIN View state ID, formula

Visualforce

FINER and above

VF_EVALUATE_FORMULA_END

None

Visualforce

FINER and above

VF_PAGE_MESSAGE

Message text

Apex Code

INFO and above

VF_SERIALIZE_VIEWSTATE_BEGIN View state ID

Visualforce

INFO and above

VF_SERIALIZE_VIEWSTATE_END None

Visualforce

INFO and above

WF_ACTION

Action description

Workflow

INFO and above

WF_ACTION_TASK

Task subject, action ID, rule, owner, due date Workflow

INFO and above

WF_ACTIONS_END

Summer of actions performed

Workflow

INFO and above

WF_APPROVAL

Transition type, EntityName: NameField Workflow


Id, process node name

INFO and above

WF_APPROVAL_REMOVE

EntityName: NameField Id

Workflow

INFO and above

WF_APPROVAL_SUBMIT

EntityName: NameField Id

Workflow

INFO and above

WF_ASSIGN

Owner, assignee template ID

Workflow

INFO and above

WF_CRITERIA_BEGIN

EntityName: NameField Id, rule name, Workflow

INFO and above

rule ID, trigger type (if rule respects trigger


types)
WF_CRITERIA_END

Boolean value indicating success (true or false) Workflow

INFO and above

WF_EMAIL_ALERT

Action ID, rule

Workflow

INFO and above

WF_EMAIL_SENT

Email template ID, recipients, CC emails

Workflow

INFO and above

WF_ENQUEUE_ACTIONS

Summary of actions enqueued

Workflow

INFO and above

WF_ESCALATION_ACTION

Case ID, business hours

Workflow

INFO and above

WF_ESCALATION_RULE

None

Workflow

INFO and above

219

Debugging Apex

Debugging Apex API Calls

Event Name

Fields or Information Logged With Event Category Logged

Level Logged

WF_EVAL_ENTRY_CRITERIA

Process name, email template ID, Boolean


value indicating result (true or false)

Workflow

INFO and above

WF_FIELD_UPDATE

EntityName: NameField Id, object or

Workflow

INFO and above

field name
WF_FORMULA

Formula source, values

Workflow

INFO and above

WF_HARD_REJECT

None

Workflow

INFO and above

WF_NEXT_APPROVER

Owner, next owner type, field

Workflow

INFO and above

WF_NO_PROCESS_FOUND

None

Workflow

INFO and above

WF_OUTBOUND_MSG

EntityName: NameField Id, action ID, Workflow

INFO and above

rule
WF_PROCESS_NODE

Process name

Workflow

INFO and above

WF_REASSIGN_RECORD

EntityName: NameField Id, owner

Workflow

INFO and above

WF_RESPONSE_NOTIFY

Notifier name, notifier email, notifier


template ID

Workflow

INFO and above

WF_RULE_ENTRY_ORDER

Integer, indicating order

Workflow

INFO and above

WF_RULE_EVAL_BEGIN

Rule type

Workflow

INFO and above

WF_RULE_EVAL_END

None

Workflow

INFO and above

WF_RULE_EVAL_VALUE

Value

Workflow

INFO and above

WF_RULE_FILTER

Filter criteria

Workflow

INFO and above

WF_RULE_INVOCATION

EntityName: NameField Id

Workflow

INFO and above

WF_RULE_NOT_EVALUATED

None

Workflow

INFO and above

WF_SOFT_REJECT

Process name

Workflow

INFO and above

WF_SPOOL_ACTION_BEGIN

Node type

Workflow

INFO and above

WF_TIME_TRIGGER

EntityName: NameField Id, time action, Workflow

INFO and above

time action container, evaluation Datetime


WF_TIME_TRIGGERS_BEGIN

None

Workflow

INFO and above

See Also:
Understanding the Debug Log

Debugging Apex API Calls


All API calls that invoke Apex support a debug facility that allows access to detailed information about the execution of the
code, including any calls to System.debug(). In addition to the Developer Console, a SOAP input header called
DebuggingHeader allows you to set the logging granularity according to the levels outlined in the following table.

220

Debugging Apex

Debugging Apex API Calls

Element Name

Type

Description

LogCategory

string

Specify the type of information returned in the debug log. Valid values are:
Db
Workflow
Validation
Callout
Apex_code
Apex_profiling
All

LogCategoryLevel

string

Specifies the amount of information returned in the debug log. Only the
Apex_code LogCategory uses the log category levels.
Valid log levels are (listed from lowest to highest):

ERROR
WARN
INFO
DEBUG
FINE
FINER
FINEST

In addition, the following log levels are still supported as part of the DebuggingHeader for backwards compatibility.
Log Level

Description

NONE

Does not include any log messages.

DEBUGONLY

Includes lower level messages, as well as messages generated by calls to the


System.debug method.

DB

Includes log messages generated by calls to the System.debug method, as well as every
data manipulation language (DML) statement or inline SOQL or SOSL query.

PROFILE

Includes log messages generated by calls to the System.debug method, every DML
statement or inline SOQL or SOSL query, and the entrance and exit of every user-defined
method. In addition, the end of the debug log contains overall profiling information for
the portions of the request that used the most resources, in terms of SOQL and SOSL
statements, DML operations, and Apex method invocations. These three sections list
the locations in the code that consumed the most time, in descending order of total
cumulative time, along with the number of times they were executed.

CALLOUT

Includes the request-response XML that the server is sending and receiving from an
external Web service. This is useful when debugging issues related to using Force.com
Web services API calls.

221

Debugging Apex

Handling Uncaught Exceptions

Log Level

Description

DETAIL

Includes all messages generated by the PROFILE level as well as the following:
Variable declaration statements
Start of loop executions
All loop controls, such as break and continue
Thrown exceptions *
Static and class initialization code *
Any changes in the with sharing context

The corresponding output header, DebuggingInfo, contains the resulting debug log. For more information, see
DebuggingHeader on page 607.

See Also:
Understanding the Debug Log

Handling Uncaught Exceptions


If some Apex code has a bug or does not catch a code-level exception:

The end user sees a simple explanation of the problem in the application interface. This error message includes the Apex
stack trace.
The developer specified in the LastModifiedBy field receives the error via email with the Apex stack trace and the
customers organization and user ID. No other customer data is returned with the report. Note that for Apex code that
runs synchronously, some error emails may get suppressed for duplicate exception errors. For Apex code that runs
asynchronouslybatch Apex, scheduled Apex, or future methods (methods annotated with @future)error emails for
duplicate exceptions dont get suppressed.

Understanding Execution Governors and Limits


Because Apex runs in a multitenant environment, the Apex runtime engine strictly enforces a number of limits to ensure that
runaway Apex does not monopolize shared resources. These limits, or governors, track and enforce the statistics outlined in
the following table. If some Apex code ever exceeds a limit, the associated governor issues a runtime exception that cannot be
handled.
Governor limits apply to an entire organization, as well as to specific namespaces. For example, if you install a managed package
created by a salesforce.com ISV Partner from Force.com AppExchange, the components in the package belong to a namespace
unique from other components in your organization. Consequently, any Apex code in that package can issue up to 150 DML
statements while executing. In addition, any Apex code that is native to your organization can also issue up to 150 DML
statements, meaning more than 150 DML statements might execute during a single request if code from the managed package
and your native organization both execute. Conversely, if you install a package from AppExchange that is not created by a
salesforce.com ISV Partner, the code from that package does not have its own separate governor limit count. Any resources
it uses counts against the total for your organization. Cumulative resource messages and warning emails are also generated

222

Debugging Apex

Understanding Execution Governors and Limits

based on managed package namespaces as well. For more information on salesforce.com ISV Partner packages, see salesforce.com
Partner Programs.
Description
Total number of SOQL queries issued

Limit
1

100
1

Total number of SOQL queries issued for Batch Apex and future methods

200

Total number of records retrieved by SOQL queries

50,000

Total number of SOSL queries issued

20

Total number of records retrieved by a single SOSL query

200

Total number of DML statements issued2

150

Total number of records processed as a result of DML statements, Approval.process, or 10,000


database.emptyRecycleBin

Total number of executed code statements

200,000

Total number of executed code statements for Batch Apex and future methods

1,000,000

Total heap size3

6 MB

Total heap size for Batch Apex and future methods

12 MB

Total stack depth for any Apex invocation that recursively fires triggers due to insert,
update, or delete statements4

16

For loop list batch size

200

Total number of callouts (HTTP requests or Web services calls) in a request

10

Maximum timeout for all callouts (HTTP requests or Web services calls) in a request

120 seconds

Default timeout of callouts (HTTP requests or Web services calls) in a request

10 seconds

Total number of methods with the future annotation allowed per Apex invocation5

10

Maximum size of callout request or response (HTTP request or Web services call)6

3 MB

Total number of sendEmail methods allowed

10

Total number of describes allowed7

100

Total number of classes that can be scheduled concurrently

25
8

Total number of test classes that can be queued per a 24hour period

The greater of 500 or 10


multiplied by the number of
test classes in the organization

In a SOQL query with parent-child relationship sub-queries, each parent-child relationship counts as an additional query.
These types of queries have a limit of three times the number for top-level queries. The row counts from these relationship
queries contribute to the row counts of the overall code execution. In addition to static SOQL statements, calls to the following
methods count against the number of SOQL statements issued in a request.

Database.countQuery

223

Debugging Apex

Understanding Execution Governors and Limits

Database.getQueryLocator
Database.query

Calls to the following methods count against the number of DML queries issued in a request.
Approval.process
Database.convertLead
Database.emptyRecycleBin
Database.rollback
Database.setSavePoint
delete and Database.delete
insert and Database.insert
merge
undelete and Database.undelete
update and Database.update
upsert and Database.upsert
System.runAs

Email services heap size is 36 MB.

Recursive Apex that does not fire any triggers with insert, update, or delete statements exists in a single invocation,
with a single stack. Conversely, recursive Apex that fires a trigger spawns the trigger in a new Apex invocation, separate from
the invocation of the code that caused it to fire. Because spawning a new invocation of Apex is a more expensive operation
than a recursive call in a single invocation, there are tighter restrictions on the stack depth of these types of recursive calls.
5

Salesforce also imposes a limit on the number of future method invocations: 200 method calls per full Salesforce user
license, Salesforce Platform user license, or Force.com - One App user license, per 24 hours. This is an organization-wide
limit. Chatter Only, Chatter customer users, Customer Portal User, and partner portal User licenses arent included in this
limit calculation. For example, suppose your organization has three full Salesforce licenses, two Salesforce Platform licenses,
and 100 Customer Portal User licenses. Your entire organization is limited to only 1,000 method calls every 24 hours ((3+2)
* 200, not 105.)
6

The HTTP request and response sizes count towards the total heap size.

Describes include the following methods and objects.

ChildRelationship objects
RecordTypeInfo objects
PicklistEntry objects
fields calls
fieldsets calls

This limit applies when you start tests asynchronously by selecting test classes for execution through the Apex Test Execution
page or by inserting ApexTestQueueItem objects using SOAP API.
Limits apply individually to each testMethod.
Use the Limits methods to determine the code execution limits for your code while it is running. For example, you can use
the getDMLStatements method to determine the number of DML statements that have already been called by your program,
or the getLimitDMLStatements method to determine the total number of DML statements available to your code.
For best performance, SOQL queries must be selective, particularly for queries inside of triggers. To avoid long execution
times, non-selective SOQL queries may be terminated by the system. Developers will receive an error message when a

224

Debugging Apex

Understanding Execution Governors and Limits

non-selective query in a trigger executes against an object that contains more than 100,000 records. To avoid this error, ensure
that the query is selective. See More Efficient SOQL Queries.
For Apex saved using Salesforce.com API version 20.0 or earlier, if an API call causes a trigger to fire, the batch of 200 records
to process is further split into batches of 100 records. For Apex saved using Salesforce.com API version 21.0 and later, no
further splits of API batches occur. Note that static variable values are reset between batches, but governor limits are not. Do
not use static variables to track state information between batches.
In addition to the execution governor limits, Apex has the following limits.

The maximum number of characters for a class is 1 million.


The maximum number of characters for a trigger is 1 million.
The maximum amount of code used by all Apex code in an organization is 2 MB.
Note: This limit does not apply to certified managed packages installed from AppExchange, (that is, an app that
has been marked AppExchange Certified). The code in those types of packages belong to a namespace unique
from the code in your organization. For more information on AppExchange Certified packages, see the Force.com
AppExchange online help.
This limit also does not apply to any code included in a class defined with the @isTest annotation.

There is a limit on the method size. Large methods that exceed the allowed limit cause an exception to be thrown during
the execution of your code. Like in Java, the method size limit in Apex is 65,535 bytecode instructions in compiled form.
If a SOQL query runs more than 120 seconds, the request can be canceled by Salesforce.
Each Apex request is limited to 10 minutes of execution.
A callout request to a given URL is limited to a maximum of 20 simultaneous requests.
The maximum number of records that an event report returns for a user who is not a system administrator is 20,000, for
system administrators, 100,000.
Each organization is allowed 10 synchronous concurrent events, each not lasting longer than 5 seconds. If additional
requests are made while 10 requests are running, it is denied.
A user can have up to 50 query cursors open at a time. For example, if 50 cursors are open and a client application still
logged in as the same user attempts to open a new one, the oldest of the 50 cursors is released. Note that this limit is
different for the batch Apex start method, which can have up to five query cursors open at a time per user. The other
batch Apex methods have the higher limit of 50 cursors.
Cursor limits for different Force.com features are tracked separately. For example, you can have 50 Apex query cursors,
50 batch cursors, and 50 Visualforce cursors open at the same time.

In a single transaction, you can only reference 10 unique namespaces. For example, suppose you have an object that executes
a class in a managed package when the object is updated. Then that class updates a second object, which in turn executes
a different class in a different package. Even though the second package wasn't accessed directly by the first, because it
occurs in the same transaction, it's included in the number of namespaces being accessed in a single transaction.
Any deployment of Apex is limited to 5,000 code units of classes and triggers.

Email Limits
Inbound Email Limits
Email Services: Maximum Number of Email Messages Processed
(Includes limit for On-Demand Email-to-Case)

Number of user licenses multiplied by


1,000, up to a daily maximum of
1,000,000

225

Debugging Apex

Understanding Execution Governors and Limits

Email Services: Maximum Size of Email Message (Body and Attachments)

10 MB1

On-Demand Email-to-Case: Maximum Email Attachment Size

10 MB

On-Demand Email-to-Case: Maximum Number of Email Messages Processed Number of user licenses multiplied by
1,000, up to a daily maximum of
(Counts toward limit for Email Services)
1,000,000
1

The maximum size of email messages for Email Services varies depending on language and character set.

When defining email services, note the following:

An email service only processes messages it receives at one of its addresses.


Salesforce limits the total number of messages that all email services combined, including On-Demand Email-to-Case,
can process daily. Messages that exceed this limit are bounced, discarded, or queued for processing the next day,
depending on how you configure the failure response settings for each email service. Salesforce calculates the limit
by multiplying the number of user licenses by 1,000, up to a daily maximum of 1,000,000. For example, if you have
ten licenses, your organization can process up to 10,000 email messages a day.
Email service addresses that you create in your sandbox cannot be copied to your production organization.
For each email service, you can tell Salesforce to send error email messages to a specified address instead of the
sender's email address.
Email services rejects email messages and notifies the sender if the email (combined body text, body HTML and
attachments) exceeds approximately 10 MB (varies depending on language and character set).

Outbound Email: Limits for Single and Mass Email Sent Using Apex
You can send single emails to a maximum of 1,000 external email addresses per day based on Greenwich Mean Time
(GMT). Single emails sent using the application don't count towards this limit.
You can send mass email to a total of 1,000 external email addresses per day per organization based on Greenwich Mean
Time (GMT). The maximum number of external addresses you can include in each mass email depends on the Edition
of Salesforce you are using:
Edition

Address Limit per Mass Email

Professional

250

Enterprise Edition

500

Unlimited Edition

1,000

Note: Note the following about email limits:

The single and mass email limits don't take unique addresses into account. For example, if you have
[email protected] in your email 10 times, that counts as 10 against the limit.
You can send an unlimited amount of email to your internal users. These limits also apply to emails sent
using the API and Apex.
In Developer Edition organizations and organizations evaluating Salesforce during a trial period, your
organization can send mass email to no more than 10 external email addresses per day. This lower limit does
not apply if your organization was created before the Winter '12 release and already had mass email enabled
with a higher limit.

226

Debugging Apex

Using Governor Limit Email Warnings

Batch Apex Governor Limits


Keep in mind the following governor limits for batch Apex:

Up to five queued or active batch jobs are allowed for Apex.


A user can have up to 50 query cursors open at a time. For example, if 50 cursors are open and a client application still
logged in as the same user attempts to open a new one, the oldest of the 50 cursors is released. Note that this limit is
different for the batch Apex start method, which can have up to five query cursors open at a time per user. The other
batch Apex methods have the higher limit of 50 cursors.
Cursor limits for different Force.com features are tracked separately. For example, you can have 50 Apex query cursors,
50 batch cursors, and 50 Visualforce cursors open at the same time.

A maximum of 50 million records can be returned in the Database.QueryLocator object. If more than 50 million
records are returned, the batch job is immediately terminated and marked as Failed.
The maximum value for the optional scope parameter is 2,000. If set to a higher value, Salesforce chunks the records
returned by the QueryLocator into smaller batches of up to 2,000 records.
If no size is specified with the optional scope parameter, Salesforce chunks the records returned by the QueryLocator
into batches of 200, and then passes each batch to the execute method. Apex governor limits are reset for each execution
of execute.
The start, execute, and finish methods can implement up to 10 callouts each.
Batch executions are limited to 10 callouts per method execution.
The maximum number of batch executions is 250,000 per 24 hours.
Only one batch Apex job's start method can run at a time in an organization. Batch jobs that havent started yet remain
in the queue until they're started. Note that this limit doesnt cause any batch job to fail and execute methods of batch
Apex jobs still run in parallel if more than one job is running.

See Also:
What are the Limitations of Apex?
Future Annotation

Using Governor Limit Email Warnings


When an end-user invokes Apex code that surpasses more than 50% of any governor limit, you can specify a user in your
organization to receive an email notification of the event with additional details. To enable email warnings:
1.
2.
3.
4.
5.

Log in to Salesforce as an administrator user.


Click Your Name > Setup > Manage Users > Users.
Click Edit next to the name of the user who should receive the email notifications.
Select the Send Apex Warning Emails option.
Click Save.

227

Chapter 9
Developing Apex in Managed Packages
In this chapter ...

Package Versions
Deprecating Apex
Behavior in Package Versions

A package is a container for something as small as an individual component or


as large as a set of related apps. After creating a package, you can distribute it to
other Salesforce users and organizations, inclu