Important Reserved Words: Keyword Description Example

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

App Logic Apex Code Cheat Sheet

Overview Important Reserved Words


Force.com Apex code is a strongly-typed programming language that executes on the
Force.com platform. Using Apex, you can add business logic to applications, write Keyword Description Example
database triggers, and program controllers used with Visualforce. Apex has a tight public class myCls {
final Defines constants and
integration with the database and query language, web service, and email handling methods that can’t be static final Integer INT_CONST;
support. It also includes features such as asynchronous execution and support for testing. overridden }

try {
Important Reserved Words finally Identifies a block of
code that is guaranteed // Your code here
to execute } catch (ListException e) {
// List Exception handling code
Keyword Description Example } finally {
// will execute with or without
abstract Declares a class public abstract class Foo { // exception
that contains abstract protected void method1() { /*… */ } }
methods that only have abstract Integer abstractMethod();
} for (Integer i = 0, j = 0; i < 10;
their signature and no for Defines a loop. The
body defined. Can also three types of for loops i++) { System.debug(i+1);
define methods. are: iteration using a }
variable, iteration over
Integer[] myInts = new Integer[]{1,
break Exits the entire loop while(reader.hasNext()) { a list, and iteration over 8, 9};
if (reader.getEventType() == END) { a query for (Integer i : myInts) {
break; System.debug(i);
}; }
// process
reader.next(); String s = 'Acme';
} for (Account a : [SELECT Id, Name,
FROM account
catch Identifies a block of try { WHERE Name LIKE :(s+'%')]) {
code that can handle // Your code here // Your code
a particular type of }
} catch (ListException e) {
exception // List Exception handling code here
global Defines a class, global class myClass {
}
method, or variable webService static void
that can be used by any makeContact(String lastName) {
class Defines a class private class Foo { // do some work
private Integer x; Apex that has access
}
public Integer getX() { return x; } to the class, not just
} the Apex in the same
application.
continue Skips to the next while (checkBoolean) {
iteration of the loop if (condition) Integer i = 1;
if Defines a condition,
{continue; } if (i > 0) {
// do some work used to determine
whether a code block // do something;
} }
should be executed
do Defines a do-while Integer count = 1;
loop that executes do { implements Declares a class global class CreateTaskEmailExample
System.debug(count); or interface that implements Messaging.
repeatedly while a
count++; implements an InboundEmailHandler {
Boolean condition } while (count < 11); global Messaging.InboundEmailResult
remains true interface
handleInboundEmail(Messaging.
inboundEmail email,
else Defines the else Integer x, sign; Messaging.InboundEnvelope env){
portion of an if-else if (x==0) { // do some work, return value;
statement, that sign = 0; }
} else {
executes if the initial sign = 1;
evaluation is untrue }
}
instanceOf Verifies at runtime if (reports.get(0) instanceof
enum Defines an public enum Season {WINTER, SPRING, CustomReport) {
SUMMER, FALL}; whether an object is
enumeration type on actually an instance of // Can safely cast
a finite set of values Season e = Season.WINTER; CustomReport c = (CustomReport)
a particular class
reports.get(0);
extends Defines a class or public class MyException extends } else {
interface that extends Exception {} // Do something with the non-
custom-report.
another class or
try { }
interface
Integer i;
if (i < 5) throw new MyException(); interface Defines a data public interface PO {
} catch (MyException e) { public void doWork();
type with
// Your MyException handling code }
} method signatures.
public class MyPO implements PO {
Classes implement
public override doWork() {
Boolean isNotTrue = false; interfaces. An interface // actual implementation
false Identifies an untrue
can extend another }
value assigned to a
interface. }
Boolean

http://developer.salesforce.com
Important Reserved Words Important Reserved Words
Keyword Description Example Keyword Description Example
new Creates a new object, Foo f = new Foo(); trigger myAccountTrigger on Account
MyObject__c mo =
trigger Defines a trigger on an
sObject, or collection sObject (before insert, before update) {
instance new MyObject__c(Name= 'hello'); if (Trigger.isBefore) {
List<Account> la = new for (Account a : Trigger.old) {
List<Account>();
if (a.Name != 'okToDelete') {
null Identifies a null constant Boolean b = null; a.addError(
that can be assigned to any 'You can\'t delete this record!');
variable }
}
override Defines a method or public virtual class V { }
property as overriding public virtual void foo()
another defined as virtual {/*Does nothing*/}
} true Identifies a true value Boolean mustIterate = true;
in a class being extended assigned to a Boolean
or implemented public class RealV implements V {
public override void foo() { try {
// Do something real
try Identifies a block of code
in which an exception // Your code here
}
} can occur
} catch (ListException e) {
// List Exception handling code
private Defines a class, method, or public class OuterClass { // here
variable that is only known // Only visible to methods and }
locally, within the section // statements within OuterClass
private static final Integer
of code in which it is webService Defines a static method global class MyWebService {
MY_INT;
defined. This is the default } that is exposed as a webService static Id makeContact(
scope for all methods and Web service method that String lastName, Account a) {
variables that do not have can be called by external
a scope defined Contact c = new Contact(
client applications. LastName = 'Weissman',
protected Defines a method or public class Foo { Web service methods AccountId = a.Id);
variable that is visible to public void quiteVisible(); can only be defined in insert c;
any inner classes in the protected void lessVisible(); a global class. return c.Id;
} }
defining Apex class
}
public Defines a method or public class Foo {
variable that can be public void quiteVisible();
private void almostInvisible(); while Executes a block of Integer count=1;
used by any Apex in this while (count < 11) {
} code repeatedly as long
application or namespace System.debug(count);
as a particular Boolean
return Returns a value from a public Integer meaningOfLife() { count++;
condition remains true
return 42; }
method
}
public class OuterClass { with Enforces sharing rules that public with sharing class
static Defines a method or sharingClass {
variable that is only // Associated with instance sharing apply to the current user.
public static final Integer If absent, code is run under // Code will enforce current user's
initialized once, and is // sharing rules
MY_INT; default system context.
associated with an (outer) }
class, and initialization // Initialization code
code static { without Ensures that the sharing public without sharing class
MY_INT = 10; noSharing {
sharing rules of the current user
} // Code won't enforce current
} are not enforced
user's
public class AnotherChildClass // sharing rules
super Invokes a constructor on a }
superclass extends InnerClass {
AnotherChildClass(String s) {
super(); virtual Defines a class or method public virtual class MyException
// different constructor, no that allows extension extends Exception {
// args // Exception class member
}
and overrides. You can’t
// variable
} override a method
public Double d;
with the override
testmethod Defines a method as a static testmethod void testFoo() { keyword unless the class or
// some test logic // Exception class constructor
unit test method has been defined MyException(Double d) {
}
as virtual. this.d = d;
this Represents the current public class Foo { }
instance of a class, or in public Foo(String s) { /* … */}
constructor chaining public foo() { // Exception class method
this('memes repeat'); } protected void doIt() {}
} }

throw Throws an exception, public class MyException extends


signaling that an error Exception {} Annotations
has occurred try {
Integer i;
if (i < 5) Annotation Description Example
throw new MyException();
} catch (MyException e) { global class MyFutureClass {
@future Denotes methods that are
// Your MyException handling @future
// code here executed asynchronously
static void myMethod(
} String a, Integer i) {
System.debug(
transient Declares instance variables transient integer currentValue; 'Method called with: ' + a +
that cannot be saved, and ' and ' + i);
should not be transmitted // do callout, other long
as part of the view state, // running code
in Visualforce controllers }
and extensions }
Annotations Primitive Types
Annotation Description Example Type Description Example
Decimal Number that includes a decimal Decimal myDecimal = 12.4567;
@isTest Denotes classes that only @isTest private class MyTest {
point. Decimal is an arbitrary Decimal divDec = myDecimal.
contain code used for // Methods for testing
precision number. divide
testing your application. }
(7, 2, System.RoundingMode.UP);
These classes don’t count system.assertEquals(divDec,
against the total amount 1.78);
of Apex used by your
Double 64-bit number that includes a Double d=3.14159;
organization.
decimal point. Minimum value
-263. Maximum value of 263-1
@isTest( Denotes a test class or test @isTest(OnInstall=true)
OnInstall=true) method that executes on private class TestClass { ID 18-character Force.com record ID id='00300000003T2PGAA0';
package installation } identifier
Integer 32-bit number that doesn’t include Integer i = 1;
@isTest( Denotes a test class or test @isTest(SeeAllData=true) a decimal point. Minimum value
SeeAllData=true) method that has access to private class TestClass { -2,147,483,648 — maximum value
all data in the organization }
of 2,147,483,647
including pre-existing data
Long 64-bit number that doesn’t include Long l = 2147483648L;
that the test didn't create.
The default is false. a decimal point. Minimum value
of -263 — maximum value of 263-1.
@deprecated Denotes methods, classes, @deprecated String Set of characters surrounded by String s = 'repeating memes';
exceptions, enums, public void limitedShelfLife() { single quotes
interfaces, or variables that } Time myTime =
can no longer be referenced
Time Particular time
Time.newInstance(18, 30, 2, 20);
in subsequent releases of Integer myMinutes = myTime.
the managed package in minute();
which they reside
Collection Types
@readOnly Denotes methods that @readOnly
can perform queries private void doQuery() {
// Create an empty list of String
unrestricted by the number } List Ordered collection
of typed primitives, List<String> my_list = new
of returned rows limit for List<String>();
a request sObjects, objects, or
collections that are My_list.add('hi');
distinguished by String x = my_list.get(0);
@remoteAction Denotes Apex controller @remoteAction
global static String getId(
their indices
methods that JavaScript // Create list of records from a query
code can call from a String s) { List<Account> accs = [SELECT Id, Name
} FROM
Visualforce page via
JavaScript remoting. The Account LIMIT 1000];
method must be static and Map Collection of key-value Map<String, String> mys = new Map<String,
either public or global. pairs where each String>();
unique key maps to a Map<String, String> mys = new Map<String,
Denotes a class that is @restResource(urlMapping= String>{'a' => 'b', 'c' => 'd'.
@restResource single value. Keys can
'/Widget/*') toUpperCase()};
available as a REST be any primitive data
resource. The class must global with sharing class type, while values can
MyResource() { Account myAcct = new Account();
be global. The urlMapping be a primitive, sObject, Map<Integer, Account> m = new
}
parameter is your resource's collection type, or an Map<Integer, Account>();
name and is relative to object. m.put(1, myAcct);
https://instance.salesforce.
com/services/apexrest/. Set Unordered collection Set<Integer> s = new Set<Integer>();
that doesn’t contain s.add(12);
@httpGet any duplicate elements. s.add(12);
@httpGet, Denotes a REST method System.assert(s.size()==1);
@httpPost, in a class annotated with global static MyWidget__c
doGet() {
@httpPatch,
@httpPut,
@restResource that the
runtime invokes when a } Trigger Context Variables
@httpDelete client sends an HTTP @httpPost
GET, POST, PATCH, PUT, or global static void doPost() { Variable Operators
DELETE respectively. }
isExecuting Returns true if the current context for the Apex code is a trigger only
The methods defined with @httpDelete
any of these annotations global static void doDelete() { isInsert Returns true if this trigger was fired due to an insert operation
must be global and static. }
isUpdate Returns true if this trigger was fired due to an update operation

Primitive Types isDelete Returns true if this trigger was fired due to a delete operation

isBefore Returns true if this trigger was fired before any record was saved
Type Description Example
isAfter Returns true if this trigger was fired after all records were saved
Blob Binary data stored as a single Blob myBlob =
object Blob.valueof('idea'); isUndelete Returns true if this trigger was fired after a record is recovered from
the Recycle Bin
Boolean Value that can only be assigned Boolean isWinner = true;
true, false, or null new Returns a list of the new versions of the sObject records. (Only in
insert and update triggers, and the records can only be modified in
Date Particular day Date myDate = Date.today(); before triggers.)
Date weekStart =
myDate.toStartofWeek(); newMap A map of IDs to the new versions of the sObject records. (Only available in
Datetime Particular day and time Datetime myDateTime = before update, after insert, and after update triggers.)
Datetime.now();
old Returns a list of the old versions of the sObject records.
Datetime newd =
myDateTime. addMonths(2); (Only available in update and delete triggers.)
Trigger Context Variables Standard Classes and Methods (Subset)
System
Variable Operators abortJob assert assertEquals
assertNotEquals currentPageReference currentTimeMillis
oldMap A map of IDs to the old versions of the sObject records. debug isRunningTest now
(Only available in update and delete triggers.) process resetPassword runAs
schedule setPassword submit today
size The total number of records in a trigger invocation, both old and new. Math
abs acos asin atan atan2 cbrt ceil
Apex Data Manipulation Language (DML) Operations cos cosh exp floor log log10 max
min mod pow random rint round roundToLong
signum sin sinh sqrt tan tanh
Keyword Description Example
Describe
insert Adds one or Lead l = new Lead(Company='ABC', fields fieldSets getChildRelationships
more records LastName='Smith'); getKeyPrefix getLabel getLabelPlural
insert l;
getLocalName getName getRecordTypeInfos
delete Deletes one or Account[] doomedAccts = [SELECT Id, Name getRecordTypeInfosByID getSobjectType
more records FROM Account WHERE Name = 'DotCom']; isAccessible getRecordTypeInfosByName
try {
delete doomedAccts; isCreateable isCustom isCustomSetting
} catch (DmlException e) { isDeletable isDeprecatedAndHidden isFeedEnabled
// Process exception here isMergeable isQueryable isSearchable
} isUndeletable isUpdateable
merge Merges up to List<Account> ls = new List<Account>{ Schema.RecordTypeInfo rtByName = rtMapByName.get(rt.name);
three records of new Account(Name='Acme Inc.'), Schema.DescribeSObjectResult d = Schema.SObjectType.Account;
the same type new Account(Name='Acme')};
insert ls; DescribeFieldResult
into one of the
Account masterAcct = [SELECT Id, Name getByteLength getCalculatedFormula getController
records, deleting FROM Account WHERE Name = 'Acme Inc.'
the others, and getDefaultValue getDefaultValueFormula getDigits
LIMIT 1];
re-parenting any Account mergeAcct = [SELECT Id, Name FROM getInlineHelpText getLabel getLength
related records Account WHERE Name = 'Acme' LIMIT 1]; getLocalName getName getPicklistValues
try { merge masterAcct mergeAcct; getPrecision getReferenceTo getRelationshipName
} catch (DmlException e) { getRelationshipOrder getScale getSOAPType
} getSObjectField getType isAccessible
isAutoNumber isCalculated isCaseSensitive
undelete Restores one or Account[] savedAccts = [SELECT Id, Name isCreateable isCustom isDefaultedOnCreate
more records from FROM Account WHERE Name = 'Trump' isDependantPicklist isDeprecatedAndHidden isExternalID
the Recycle Bin ALL ROWS]; isFilterable isGroupable isHtmlFormatted
try { undelete savedAccts;
} catch (DmlException e) { isIdLookup isNameField isNamePointing
} isNillable isPermissionable isRestrictedDelete
isRestrictedPicklist isSortable isUnique
update Modifies one or Account a = new Account(Name='Acme2');
insert(a); isUpdateable isWriteRequiresMasterRead
more existing Schema.DescribeFieldResult f = Schema.SObjectType.Account.fields.Name;
records Account myAcct = [SELECT Id, Name,
BillingCity FROM Account WHERE Name
= 'Acme2' LIMIT 1]; LoggingLevel
myAcct.BillingCity = 'San Francisco'; ERROR WARN INFO DEBUG FINE FINER FINEST
try {
update myAcct; getAggregateQueries getLimitAggregateQueries
} catch (DmlException e) { getCallouts getLimitCallouts
} getChildRelationshipsDescribes getDMLRows
upsert Creates new Account[] acctsList = [SELECT Id, Name, getLimitChildRelationshipsDescribes getLimitDMLRows
records and BillingCity FROM Account WHERE getCPUTime getLimitCPUTime
updates existing BillingCity = 'Bombay']; getDMLRows getLimitDMLRows
for (Account a : acctsList) getDMLStatements getLimitDMLStatements
records
{a.BillingCity = 'Mumbai';}
Account newAcct = new Account( getEmailInvocations getLimitEmailInvocations
Name = 'Acme', BillingCity = getFieldsDescribes getLimitFieldsDescribes
'San Francisco'); getFindSimilarCalls getLimitFindSimilarCalls
acctsList.add(newAcct); getFutureCalls getLimitFutureCalls
try { upsert acctsList; getHeapSize getLimitHeapSize
} catch (DmlException e) { getPicklistDescribes getLimitPicklistDescribes
}
getQueries getLimitQueries
getQueryLocatorRows getLimitQueryLocatorRows
Standard Interfaces (Subset) getQueryRows getLimitQueryRows
getRecordTypesDescribes getLimitRecordTypesDescribes
Database.Batchable getRunAs getLimitRunAs
global (Database.QueryLocator | Iterable<sObject>) getSavepointRollbacks getLimitSavepointRollbacks
start(Database.BatchableContext bc) {}
getSavepoints getLimitSavepoints
global void execute(Database.BatchableContext BC, list<P>){}
global void finish(Database.BatchableContext BC){} getScriptStatements getLimitScriptStatements
getSoslQueries getLimitSoslQueries
Schedulable
global void execute(ScheduleableContext SC) {} UserInfo
getDefaultCurrency getFirstName getLanguage
Messaging.InboundEmailHandler getLastName getLocale getName
global Messaging.InboundEmailResult handleInboundEmail(Messaging. getOrganizationId getOrganizationName getProfileId
inboundEmail email, Messaging.InboundEnvelope env){} getSessionId getUITheme getUIThemeDisplayed
IsMultiCurrencyOrganization
Comparable String result = UserInfo.getLocale();
global Integer compareTo(Object compareTo) {} System.assertEquals('en_US', result);

For other cheatsheets: http://developer.force.com/cheatsheets 11182013

You might also like