Coding Standards
Coding Standards
January 2017
Version 1.2
Table of Contents
Whitepaper Series.................................................................................................................. 5
Scope ...................................................................................................................................... 5
Executive Summary ............................................................................................................... 5
High Level Principles............................................................................................................. 6
Declarative Standards ........................................................................................................... 6
Enterprise Objects vs Project Objects .................................................................................. 6
General Naming Convention ................................................................................................ 6
Objects.............................................................................................................................. 7
Custom Fields ................................................................................................................... 8
Visualforce Pages ............................................................................................................. 8
Example: ........................................................................................................................... 8
Apex Classes .................................................................................................................... 8
Apex Methods ................................................................................................................... 9
Apex Variables.................................................................................................................. 9
Apex Constants ................................................................................................................ 9
Approval Processes .......................................................................................................... 9
Approval Process Steps ................................................................................................. 10
Workflow rules ................................................................................................................ 10
Field Updates.................................................................................................................. 10
Validation Rules .............................................................................................................. 10
Page Layout.................................................................................................................... 10
Record Types ................................................................................................................. 10
Buttons and Links ........................................................................................................... 10
Coding Standards ................................................................................................................ 11
Apex Classes ..................................................................................................................... 11
Methods.............................................................................................................................. 12
Static Variable .................................................................................................................... 13
Workflow rules and Triggers............................................................................................... 13
Code Blocks ....................................................................................................................... 13
Class length........................................................................................................................ 14
Method length .................................................................................................................... 14
2 of 34
Salesforce Coding Standards
Parameter lists ................................................................................................................... 14
Excessive Fields................................................................................................................. 14
String Literals ..................................................................................................................... 15
String Conversion ............................................................................................................... 15
If Statements ...................................................................................................................... 15
Exceptions .......................................................................................................................... 15
Exception Handlers ............................................................................................................ 17
ApplicationLog__c .......................................................................................................... 19
Apex Global Variables ........................................................................................................ 19
SOQL inside loops ............................................................................................................. 19
Querying Large Data sets .................................................................................................. 21
Debug Logs ........................................................................................................................ 21
Code Convention ................................................................................................................. 22
General Standards ............................................................................................................. 22
Comments .......................................................................................................................... 22
Apex................................................................................................................................ 23
VisualForce ..................................................................................................................... 24
Javascript........................................................................................................................ 24
CSS ................................................................................................................................ 24
Indentation.......................................................................................................................... 24
Unit Test Coverage ............................................................................................................ 25
Additional Rules ................................................................................................................. 26
User Interface ..................................................................................................................... 27
JavaScript........................................................................................................................... 27
Triggers .............................................................................................................................. 27
@future .............................................................................................................................. 28
Cyclomatic complexity ........................................................................................................ 29
Visualforce Pages/ Components ........................................................................................ 29
Page Layout ....................................................................................................................... 29
General Convention ........................................................................................................... 30
Canvas .................................................................................................................................. 30
Lightning Components........................................................................................................ 30
Code security and Safety .................................................................................................... 30
Standard Visualforce components ..................................................................................... 31
3 of 34
Salesforce Coding Standards
Programming Items Not Protected from XSS .................................................................... 31
Custom JavaScript.......................................................................................................... 31
<apex:includeScript> ...................................................................................................... 31
Formula Tags.................................................................................................................. 32
Cross-Site Request Forgery (CSRF).................................................................................. 32
SOQL Injection ................................................................................................................... 33
Data Access Control........................................................................................................... 33
Development Processes ..................................................................................................... 34
Reference Documentation .................................................................................................. 34
About the Author ................................................................................................................. 34
4 of 34
Salesforce Coding Standards
Whitepaper Series
This document is one of a series of Whitepaper on the Salesforce Software Development
Lifecycle. The complete series is:
1. Introduction to Salesforce Software Development Lifecycle
2. Agile development – how to carry out agile development with Salesforce technology,
including the basics of scrum
3. Environmental Management – This cover roadmap planning and Sandbox
architecture
4. Best Practices – Development, Configuration and coding
5. Release Management – the processes and tools to migrate from Development, Test,
UAT, Production, including source control and Continuous delivery
6. Testing Strategy and Tooling – the processes and tools need to carry out
comprehensive testing on the Salesforce Platform
7. Citizen Development – discusses the processes to enable Citizen developers within
your company
8. Coding Standards – comprehensive set of Salesforce coding standards (this
document)
Scope
This document defines best practices for developing “Classic” Salesforce technology, see
associated documents for other technology. (“Classic” refers to Salesforce technology that
runs on the Force.com platform) for an introduction to the topic please review Development
Lifecycle Guide
Executive Summary
The consistent and well-written code is critical to ensuring high quality standards across all
applications. The declarative standards will allow for the platform to be self-documented and
allow for future applications to build on the existing functionality without the need for
extensive rework.
Following the standards outlined in this document is fundamental to the development
process, and every member of the technical staff should know and follow them at all times.
• Developers need to read, understand and execute to these standards.
• Project Managers/Team Leaders need to verify that their developers have followed
these standards.
• Code that is not delivered to these standards should not be deployed.
Lightning components are not currently included within this standards document but will be
for a later version.
5 of 34
Salesforce Coding Standards
High Level Principles
• The code compiles with no errors or warnings.
• All code is committed to the approved source control. Commits are atomic and
frequent, are accompanied by a short description of the change, and are pushed to
the remote repository at least daily.
• Naming Conventions are adhered to.
• Never store a username and/or password in code or source control.
• Never hard coded Salesforce IDs or URLs in code.
• All code must have 95% or above code coverage using the ITC Testing Strategy.
• Always use the latest generally available version of the Salesforce API and if a
current class is updated it should be saved in the current API version.
• Follow the code commenting guidelines.
• Code must provide proper Error and Execution Handling.
• Security audits must be performed with appropriate tools.
• All triggers should be bulkified.
The Product Owner for each project retains ultimate control of the standards and may
overrule this document on request in specific cases.
Declarative Standards
Enterprise Objects vs Project Objects
In general, metadata entities will either be of scope Enterprise or Project. Enterprise scope is
objects which will be used by multiple applications and will include Standard objects,
whereas Project objects will only be used within a specific application. The Data Architect
will determine which entities are of which type during the engagement via regular Data
Architectural reviews.
• Creation and/or changes to Project Objects are permitted by the project team only.
• The Data Architect may promote Project Objects to Enterprise Objects.
• Changes may not be made to Enterprise Objects without the agreement of the Data
Architect team.
• All Standard Objects are Enterprise Objects.
• Project Objects may not duplicate existing Enterprise Objects.
• Projects may not duplicate classes/approval processes/pages etc that function upon
Enterprise Objects.
• Projects that need to create/update functionality that interacts with Enterprise Objects
are responsible for engaging with the Design Authority for review and risk
management.
• The naming of Project Objects must have a unique prefix eg xxx_Territory__c.
6 of 34
Salesforce Coding Standards
• We want to ensure that the Org is self-documented. Where description fields are
available in the standard configuration it will be required to be completed.
• Aside from loop iterators such as i, j, and k, variable names, object names, class
names, and method names should always be descriptive. Single-letter names are not
acceptable.
• Class names should use CapitalizedCamelCase. Method or Function names should
use lowerCamelCase. Constants should be CAPITALIZED_WITH_UNDERSCORES.
• Underscores should not be used for any variable name, object name, class name or
method name except as an application prefix.
• Abbreviations should be avoided for all names due to the risk of misinterpretation.
• Overriding standard tabs, objects and standard names are not allowed without CoE
Core Management team approval.
• Description fields for all objects, fields and other metadata should be populated
where provided.
• Name must be meaningful. Abbreviations in names must be avoided. Like:
Objects
Naming standards for objects will start with the project name followed by a meaningful object
name. Object names will start with a capital letter.
xxx_Territory__c
Territory__c
7 of 34
Salesforce Coding Standards
Consider there are governor limits in place controlling the total characters of code included in
our code base to ensure variables are meaningful but not overly verbose. However if
required this governor limit can be increased easily. All objects are written in English.
Custom Fields
Custom field names should be CamelCase. Whole words should be used and use of
acronyms and abbreviations should be limited.
Requires project prefix for Project Custom Fields, within Project, Standard and Enterprise
Objects.:
Visualforce Pages
Names should be unique CamelCase. They should include the core object name and the
action the page performs. The Visualforce description field must be completed. (Note this
has to be done via the developer console. Tools like eclipse do not complete the description
field.
Requires project prefix:
xxx_NewsView
xxx_NewsCreate
xxx_NewsApp
Example:
Ap1_Building_NewsView
Where
• Ap1 – Application Prefix.
• Building – is the Project custom object.
• NewsView – it is a description of the VisualForce page.
Apex Classes
Classes should be unique CamelCase
1. Apex classes that are custom controller classes should be suffixed with _CC.
2. Apex classes that are controller extensions should be suffixed with _CX.
3. Apex classes that are batch classes should be suffixed with _Batch.
4. Apex classes that are schedulable batch interfaces should be suffixed with
_BatchSchedule.
8 of 34
Salesforce Coding Standards
5. Apex classes that are test classes should be suffixed with _Test after all other
suffixes.
6. All classes should have an application prefix.
Example:
xxx_Customer
xxx_Customer_CX
xxx_Customer_CC
xxx_LicenseExpiry_Batch
xxx_LicenseExpiry_BatchSchedule
xxx_Customer_Test
xxx_LicenseExpiry_Batch_Test
Apex Methods
Method names should be lowerCamelCase: verb followed by nouns. The name should be
without underscores or spaces:
xxx_handleExpiry
deleteCustomer
getLicense
Apex Variables
Variables should be lowerCamelCase. They should be descriptive in name – apart from
iterators/counters which can be single letters:
Apex Constants
Variables should be uppercase and underscore delimited. They should be descriptive in the
name:
MAX_CHARACTERS
Approval Processes
Names should be CamelCase – including the object noun and the triggering event:
xxx_ArticlePublishRequest
9 of 34
Salesforce Coding Standards
Approval Process Steps
Names should be Capitalised Clear Text with the step outcome and a description:
Workflow rules
Names should be Capitalised Clear Text with the event clearly identifiable:
xxx_Customer Verified
xxx_Account Authorized
Field Updates
Names should be Capitalised Clear Text with the field and value detailed: Set <Field> to
<Value>:
Validation Rules
Names should be CamelCase with the Field and Rule clearly identifiable:
xxx_DateInFuture
xxx_FirstNameRequired
The validation description field must be completed. When the validation rule is updated then
the description field needs to be updated.
Page Layout
Naming convention will be to identify the project that initially created the page layout. Best
practice to limit page layout and use field level security for accessing fields. Project prefixes
required.
Record Types
Record type label will be business focused and description must add to the business value.
Project Prefixes required.
10 of 34
Salesforce Coding Standards
Coding Standards
Coding standards are intended for developers who will be developing code into their Org. It
must be noted that these standards are not strictly enforced, rather a means to provide code
consistency and adherence to Salesforce best practices and will be verified during the
regular project code reviews.
Enforcing standards have the following benefits:
• Easily maintainable code.
• Delivery consistency.
• Adherence to best practices that results in improved code performance.
Apex Classes
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, but this practice is not recommended.
/*****************************************************************
Name: ConfigureOpportunity()
Copyright © 2016 ITC
============================================================
Purpose:
============================================================
History
-------
VERSION AUTHOR DATE DETAIL Description
1.0 Name dd/mm/yyyy Created CSR:
*****************************************************************/
<access> class <name>
{
//Static Block
{
//Static variable
//Static Methods
}
//Non-Static Variables
..
// Constructors
..
// getter & setter methods
..
// Action Methods
..
// Logical Methods
11 of 34
Salesforce Coding Standards
// Inner Classes and Functions
}
Methods
Methods must have a try-catch-finally block to handle possible exceptions. The try-catch
block must appear at logical places where you are sure of Exception nature and its handling.
Methods must have Debug statements in the beginning and at the end or before the return.
This must also include Input and Output parameters to help debugging the code (as shown
in the example below). Methods must have block comments to capture the details in format
shown:
History
--------
VERSION AUTHOR DATE DETAIL Description
1.0 Name dd/mm/yyyy Created CSR:
*****************************************************************/
public String addUDAC(param1, param2)
{
system.debug(‘Entering <Method Name>: ‘+ <I/P parameters>);
…
system.debug(‘Exiting <Method Name>: ‘+ <return value if any>);
return ..;
}
}
The naming convention for the getter and setter methods of Class variables is "get"/"set"
followed by the variable name, with the first letter of the name capitalized.
For example, the instance variable "customerID", can have the following formats for the
getter and setter methods:
12 of 34
Salesforce Coding Standards
public string customerID; // Variable declaration section
Static Variable
Never hard code an Id, link etc. in the code directly. Use Custom Labels or static Apex
Classes as a mechanism to drive values for a variable.
Code Blocks
Always use braces to surround code blocks (eg if…else, while, for) and add a description of
the functionality of the block.
Never use the pattern:
If ([condition])
//do something
else
//do something else
Always use:
If ([condition])
{
//do something
}
else
{
//do something else
}
13 of 34
Salesforce Coding Standards
If([condition]) {
} else {
//do something
}
Class length
Excessive class file lengths are usually indications that the class may be burdened with
excessive responsibilities that could be provided by external classes or functions. In
breaking these methods apart the code becomes more manageable and ripe for reuse.
Try to reduce the method length by creating helper methods and removing any copy/pasted
code.
Method length
Avoid long methods and classes – if necessary refactor the code.
When methods are excessively long this usually indicates that the method is doing more
than its name/signature might suggest. They also become challenging for others to digest
since excessive scrolling causes readers to lose focus. Best practice is to keep the length to
less than 2 screens approximate 60 lines, this enables clear readability and hence
maintainability.
Parameter lists
Methods with numerous parameters are a challenge to maintain, especially if most of them
share the same datatype. These situations usually denote the need for new objects to wrap
the numerous parameters.
Excessive Fields
Classes that have too many fields can become unwieldy and could be redesigned to have
fewer fields, possibly through grouping related fields in new objects.
For example, consider:
Vs:
14 of 34
Salesforce Coding Standards
String Literals
Code containing string literals can usually be improved by declaring the String as a constant
for ease of maintenance – particularly where it is duplicated. The exception here is for
SOQL statements.
String Conversion
Do not convert literals to strings by concatenating them with strings. Use one of the type-
specific toString() methods instead:
If Statements
Avoid creating deeply nested if-then statements since they are harder to read and error-
prone to maintain:
if (x>y) {
if (y>z) {
if (z==x) {
// !! too deep
}
}
}
}
Exceptions
Please refer to “Salesforce Apex Language reference” for details on Exception types,
methods and classes as listed below:
• Exception Class.
• Common Exception Methods.
• DMLException and EmailException Methods.
• Bulk DML Exception handling.
• Exception Statements:
o Throw Statements.
o Try-Catch-Finally Statements.
• Trigger Exceptions.
• Handling Uncaught Exceptions.
Do not throw raw exceptions. Throw either standard typed or custom exceptions:
15 of 34
Salesforce Coding Standards
public class MyException extends Exception{}
try
{
throw new MyException();
}
catch ( MyException e )
{
//MyException handling code here
}
try
{
// do something
}
catch (SomeException se)
{
throw se; //Do not do this
throw new SomeException(se); //nor this
}
try
{
// Here do some stuff
}
catch( Exception e)
{
// Handling the issue
}
finally
{
//Avoid doing this
throw new Exception();
}
Don’t needlessly access Exception values unless you’re going to use them. Don’t do this:
try {
16 of 34
Salesforce Coding Standards
// do something
} catch (SomeException se) {
se.getMessage();
}
try {
// do something
} catch (SomeException se) {
ApexPages.addMessages(se);
}
Exception Handlers
Use try-catch block when you know the nature of exception and want to handle it
accordingly. While handling such exceptions you must display error messages
understandable to the end user.
Examples: Use try-catch block for all API calls and based on the severity you interrupt the
processing by display the meaningful message on UI.
In remaining cases, where you are not sure of the Exception and its cause, let the exception
to be caught by Salesforce. It sends an email message with the details of the Error occurred
like the method name, line number, and type of error. It also displays an Error message on
the UI, but that may not be meaningful for the end user. The email message helps track the
error while debugging.
Uncaught Exceptions:
There is no standard way to store exception logs in Salesforce.com. By default, all uncaught
Exceptions will be flagged to the UI and an email with a brief error description will be sent to
the developer/user specified in the LastModifiedBy field. This way we lose valuable
exception log details, which will be required later for the debugging.
Caught Exceptions:
If handled in a try-catch block, the exception logs can be stored in a Custom Object and a
meaningful message can be displayed on the UI to end user. This customized error logging
process includes following:
• Store error messages and related information in a Custom object. The custom object
will store severity, error type, user, and other related details.
• Use Workflows to send an email notification whenever a user encounters error based
on the error severity.
• Cleanup or Archive error data have custom reports created to generate errors based
on status and severity.
17 of 34
Salesforce Coding Standards
Errors and exceptions must be handled in a way that provides the user with information
regarding what went wrong AND what they should do about it. Whenever possible, this error
should also be logged, so the user can provide detailed information regarding the nature of
the issue he or she encountered. Exception handlers should trap typed exceptions where
possible:
Try
{
//do something here that could throw exception
}
catch (DMLException e)
{
//log then do something
}
catch (Exception e)
{
//log then do something else
}
finally
{
// cleanup
}
Do not return from a finally block as you may lose exceptions in the process:
18 of 34
Salesforce Coding Standards
• Bulk log messages should be collated and passed to the Log in one call to prevent
excessive DML calls.
• Page based exceptions should be added to ApexPages.Messages.
• In triggers, exceptions should use addError() method to prevent committing.
• Do not catch NullPointerExceptions – identify and resolve the core issue.
ApplicationLog__c
Field Type Required Description
Age of the record in days (used to purge the
Age Formula N
table)
DebugLevel Picklist Y Error, Info, Warning, Debug
IntegrationPayload Long Text Area N If log is integration related show payload
Either the exception error code of custom org
LogCode Text (50) N
code for record
Message Long Text Area N Message to log
ReferenceId Text (18) N The related record id
The related record info (e.g. Apex Batch Job
ReferenceInfo Text (255) N
Id, Contact etc)
The originating class (e.g.
Source Text (150) Y
CustomerManagement)
The originating function in the class (e.g.
SourceFunction Text (200) Y
UpdateDivision() )
Raw exception stack trace for unhandled
StackTrace Long Text Area N
errors
The time in milliseconds for the transaction
Timer Number (18,0) N (e.g. For integration/batch apex messages it
might be the time taken to process)
<apex:outputLink value="{!$Page.otherPage}">
Instead of:
19 of 34
Salesforce Coding Standards
for (Account a : [SELECT Id, Name FROM Account
WHERE Name LIKE 'Acme%'])
{
// Your code without DML statements here
a.Name=’new name’;
update a;
}
Instead do:
}
}
Instead do:
20 of 34
Salesforce Coding Standards
Set<Id> accountIds = new Set<Id>();
for(Contact ct: Trigger.new)
{
accountIds.add(ct.AccountId);
}
//Do SOQL Query outside the iterator
Map<Id, Account> accounts = new Map<Id, Account>(
[select id, name, billingState from Account where id in
:accountIds]);
Use:
Debug Logs
The standard System Log console displays the debug log for any Apex scripts that execute
due to a trigger or from code that you entered into the text entry area at the bottom of the
System Log console.
You can retain as well as manage the debug logs for specific users in your organization.
Each debug-monitored user will record up to 20 debug logs; debug logs will stop being
21 of 34
Salesforce Coding Standards
recorded when the user reaches that limit. Each debug log will contain up to 2mb of data;
older log lines will be removed to make room for new ones. Each organization can retain up
to 50mb of debug logs; older logs will be removed to make room for newer ones.
Code Convention
General Standards
• Declare all variables at the beginning of each class.
• All instance variables must be declared either private or protected.
• A class must have limited public variables except 'final' or 'static final'. Try to avoid
public variables where possible.
• To convert a primitive type to String use String.valueOf() instead of var + "".
• Avoid any type of hard coding in the code. Use Custom Labels or static Apex
Classes to drive any configuration related values.
• Explicitly initialize local and instance variables to their default values.
String: default value is null
Integer: default value is 0
Double: 0.0 or else it assigns null by default
Boolean: false
Any other Object: null
Date: null
• Do not instantiate any object before you actually need it. Generally, consider the
scope of the variable and minimize where possible.
• All constants must have uppercase names, with logical sections of the name
separated by underscores.
• Local variables must not have the same name as instance variables. In general,
variables in a nested scope must not have the same name as variables in outer
scopes.
• Use sets, maps, or lists when returning data from the database. This makes your
code more efficient because the code makes fewer trips to the database.
• Avoid writing a SOQL inside a loop.
• All classes that contain methods or variables defined with the webService keyword
must be declared as global. If a method, variable or inner class is declared as global,
the outer, top-level class must also be defined as global.
Comments
Comments in code are important because they allow other developers to quickly
comprehend the logic and intent of the unfamiliar code. Avoid sentence fragments. Start
sentences with a properly capitalized word, and end them with punctuation.
All source code files (of all languages and/or resource types) should have a comment block
at the top that specifies the name of the class (or interface, etc.), what it does when it was
created, and who created it. If you make significant changes to a file that someone else
originally wrote, add yourself to the author line.
22 of 34
Salesforce Coding Standards
All methods should have comments explaining what they do, including information about the
input parameters and return data (if applicable). Comments should be added to methods
whenever the logic or functionality of a section of code is not immediately obvious.
Block comments are used to provide descriptions of files, methods, data structures and
algorithms. Block comments inside a function or method must be indented to the same level
as the code they describe. Remember all code, Apex, Visualforce, JavaScript, CSS should
have comments.
Single line short comments can appear on a single line indented to the level of the code that
follows:
if (condition) {
// Handle the condition.
...
}
Very short comments can appear on the same line as the code they describe:
if (a == 2) {
return TRUE; // special case
} else {
return isPrime(a); // works only for odd a
}
Apex
23 of 34
Salesforce Coding Standards
VisualForce
<apex:page standardController="Contact">
<!-- Here is a comment -->
<apex:sectionHeader title="Contact Edit" subtitle="New SFDC99 Member" />
Javascript
/**
* Returns an object as a JSON string
*
* @method toJSON
* @return {Object} Copy of ...
*/
toJSON: function () {
CSS
p{
color: red;
/* This is a single-line comment */
text-align: center;
}
/* This is a multi-line
Comment */
Indentation
• Use Tabs (4 spaces) for indentation. Set you editor tab to 4 spaces.
• Avoid lines longer than 80 characters, since they’re not handled well by many
terminals and tools.
• Split lines occur when a statement exceed the 80 column limit given above. It is
difficult to give rigid rules for how lines should be split, but the examples above
should give a general hint.
• In general:
o Break after a comma.
o Break after an operator.
o Align the new line with the beginning of the expression on the previous line.
24 of 34
Salesforce Coding Standards
//USE THIS INDENTATION INSTEAD
longName1 = longName2 * (longName3 + longName4 - longName5)
+ 4 * longname6;
@isTest
Public class myClass_Test{
// Methods for testing
@isTest static void test1() {
// Implement test code
}
}
Or:
25 of 34
Salesforce Coding Standards
// Implement test code
}
}
Additional Rules
• Make sure that each Page items(all VisualForce tags) has ID and the IDs is unique.
• Pay attention to the comments and remarks and put them in legible form before
every Page item.
• You can use global variables to reference general information about the current user
and your organization on a Visualforce page. All global variables must be included in
expression syntax, for example, {!$User.Name}.
26 of 34
Salesforce Coding Standards
• The <apex: includeScript> Visualforce component allows you to include a custom
script on the page. In these cases, careful measures need to be taken to validate that
the content is safe and does not include user-supplied data.
• The alignments have to be properly maintained with a tab of 4 spaces.
• It is recommended to have a partial rendering of a page item then a full page.
User Interface
• By default, all pages will use standard Salesforce look and feel. Any customization in
this must be discussed with the Design Authority to maintain uniform page layouts in
all modules.
• If customization of the page is required, then, External CSS must be used - Inline
and/or Internal CSS may not be used apart from for base rendering.
• Modifying the Salesforce CSS is not permitted.
• For pages that don't use Salesforce CSS files, set the tag’s showHeaders and
standardStylesheets attributes to false. This practice excludes the standard
Salesforce CSS files from the generated page header.
• Review the guidelines from Google PageSpeed Insights (Note that these standards
still are dominant where there is a discrepancy).
JavaScript
Use of third party JavaScript frameworks such as jQuery are acceptable however their use
should be considered an architecturally significant inclusion for agreement:
• Load libraries from Salesforce static resources not from external CDNs.
• Use NoConflict modes as available to avoid overriding $.
• Use shared static resources as libraries for repeated code.
• If possible, load JavaScript libraries at end of page.
• User-Agent sniffing should be avoided – instead, consider using Modernizr for
feature detection.
• Avoid excessive chaining of methods as they make reading code overly complex.
$($(event.target).parents(‘.wrapper’)[0]).find(‘.record’).find(“.customerid”).innerText
().toLowerCase()
jQuery.bind();
document.addEventListener()
Triggers
Name of a Trigger can consist of alphanumeric characters. It should be unique, beginning
with an uppercase letter and start with the <Object Name>. It should not contain
underscores and spaces apart from the Application Prefix. The words should be
concatenated with Initial uppercase.
27 of 34
Salesforce Coding Standards
There should only be one trigger per action on an object. The trigger name must be simply
the object name and the action. Use trigger handlers to link multiple logical triggers to an
event:
• Create a single trigger per object. Since Trigger execution order is impossible to
predict or control, the best practice is that one trigger per object is best practice. The
single Trigger will use Trigger Context Variables to execute delegate class utility
methods that contain the desired logic. This also creates must better maintainable
code.
• All triggers must be bulkified and test classes must test the bulkification – regardless
of a project’s expectation for bulk invocation.
• In addition, it must be possible to turn off the complete trigger via a custom setting
and static variable.
• It must be possible to stop component parts of project functionality in a trigger via a
custom setting and static variable.
• User-defined methods in a trigger cannot be declared as static.
• Use sets, maps, or lists when returning data from the database. This makes your
code more efficient because the code makes fewer trips to the database.
• You can only set five savepoints in all contexts.
• 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.
• If a Trigger is required to make an external call it must be done asynchronously using
@future.
• For complex triggers suggest you develop a trigger handler framework, see SFDC
trigger framework as an example.
@future
To run Apex asynchronously, use the @future annotation when defining the Apex method.
By default, Apex runs synchronously in a single transaction. The key benefit of running the
Apex asynchronously is to remove the business logic from the synchronous transaction and
therefore the user won't have to wait for the processing. In other words, offloading the
business logic processing to the async Apex, there is less logic to process synchronously
and the user experience is more efficient.
Even though Apex written within an asynchronous method gets its own independent set of
higher governor limits, it still has governor limits. Additionally, no more than 10 @future
methods can be invoked within a single Apex transaction.
Here is a list of governor limits specific to the @future annotation:
• No more than 10 method calls per Apex invocation.
• No more than 200 method calls per Salesforce license per 24 hours.
• The parameters specified must be primitive datatypes, arrays of primitive datatypes,
or collections of primitive datatypes.
28 of 34
Salesforce Coding Standards
• 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.
Cyclomatic complexity1
Cyclomatic complexity is a measure of the potential code routes through a piece of code. A
high value makes testing and maintenance very harder. Use a tool (such as SonarQube) to
measure cyclomatic complexity and refactor if the measure approaches or exceeds 200.
Page Layout
1
https://en.wikipedia.org/wiki/Cyclomatic_complexity
29 of 34
Salesforce Coding Standards
<apex:pageblockSectionItem>
<apex:outputLabel value="Feature Category:" for="category"/>
<apex:selectList value="{!category}" size="1" id="category">
<apex:selectOptions value="{!categories}"/>
</apex:selectList>
</apex:pageblockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
General Convention
• Make sure that each Page items(all visualforce tags) has ID and the IDs should be
unique.
• Pay attention to the comments and remarks and put them in legible form before
every Page item.
• You can use global variables to reference general information about the current user
and your organization on a Visualforce page. All global variables must be included in
expression syntax, for example, {!$User.Name}.
• The <apex: includeScript> Visualforce component allows you to include a custom
script on the page. In these cases, careful measures need to be taken to validate that
the content is safe and does not include user-supplied data.
• The alignments have to be properly maintained with a tab of 4 spaces.
• It is recommended to have a partial rendering of a page item then a full page.
• By default, all pages will use standard Salesforce look and feel. Any customization in
this must be discussed across the scrum to maintain uniform page layouts in all
modules.
• Note: If the performance of the page load is an issue, complex code documentation
may an issue, however it is important to have documentation.
Canvas
To be completed later
Lightning Components
To be completed later
30 of 34
Salesforce Coding Standards
Security audits for Apex code should be done with the Checkmarx tool at
http://security.force.com/. Running Checkmarx regularly should be an integral part of every
sprint to identify issues.
<apex:outputText>
{!$CurrentPage.parameters.userInput}
</apex:outputText>
By default, virtually all Visualforce tags escape the XSS-vulnerable characters. It is possible
to disable this behaviour by setting the optional attribute escape="false". This default
behaviour must not be disabled without ITC Core Management Team and Security Approval.
Custom JavaScript
If you write your own JavaScript, the platform has no way to protect you. For example, the
following code is vulnerable to XSS if used in JavaScript. Care should be taken when using
JavaScript, and code must be subject to rigorous QA where such methods are used.
<script>
var foo = location.search;
document.write(foo);
</script>
<apex:includeScript>
The <apex:includeScript> Visualforce component allows you to include a custom script
on the page. In these cases, ensure the content is safe and does not include user-supplied
data. For example, the following snippet is extremely vulnerable because it includes user-
supplied input as the value of the script text. The value provided by the tag is a URL to the
JavaScript to include. If an attacker can supply arbitrary data to this parameter, they can
potentially direct the victim to include any JavaScript file from any other website.
31 of 34
Salesforce Coding Standards
<apex:includeScript value="{!$CurrentPage.parameters.userInput}" />
Formula Tags
The general syntax of these tags is:{!FUNCTION()} or {!$OBJECT.ATTRIBUTE}.
Formula expressions can be function calls or include information about platform objects, a
user's environment, system environment, and the request environment. An important feature
of these expressions is that data is not escaped during rendering. Since expressions are
rendered on the server, it is not possible to escape rendered data on the client using
JavaScript or other client-side technology. This can lead to potentially dangerous situations if
the formula expression references non-system data (that is potentially hostile or editable
data) and the expression itself is not wrapped in a function to escape the output during
rendering.
Formula tags can also be used to include platform object data. Although the data is taken
directly from the user's organization, it must still be escaped before use to prevent users
from executing code in the context of other users (potentially those with higher privilege
levels). While these types of attacks must be performed by users within the same
organization, they undermine the organization's user roles and reduce the integrity of
auditing records. Additionally, many organizations contain data which has been imported
from external sources and might not have been screened for malicious content.
Within the Salesforce platform, Salesforce has implemented an anti-CSRF token to prevent
this attack. Every page includes a random string of characters as a hidden form field. Upon
the next page load, the application checks the validity of this string of characters and does
not execute the command unless the value matches the expected value. This feature
protects you when using all of the standard controllers and methods.
Developers must not bypass these built-in defences, either deliberately or inadvertently.
Developers should be cautious about writing pages that take action based upon a user-
supplied parameter.
32 of 34
Salesforce Coding Standards
SOQL Injection
In other programming languages, the previous flaw is known as SQL injection. Apex does
not use SQL but uses its own database query language, SOQL. SOQL is much simpler and
more limited in functionality than SQL. Therefore, the risks are much lower for SOQL
injection than for SQL injection, but the attacks are nearly identical to traditional SQL
injection.
In summary SQL/SOQL injection involves taking user-supplied input and using those values
in a dynamic SOQL query. If the input is not validated, it can include SOQL commands that
effectively modify the SOQL statement and trick the application into performing unintended
commands.
To prevent a SOQL injection attack, dynamic SOQL queries should not be used. Instead,
use static queries and binding variables.
If you must use dynamic SOQL, you must use the escapeSingleQuotes method to
sanitize user-supplied input. 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.
When using an Apex class, the built-in user permissions, and field-level security restrictions
are not respected during execution. The default behaviour is that an Apex class has the
ability to read and update all data within the organization. Because these rules are not
enforced, developers who use Apex must take care that they do not inadvertently expose
sensitive data that would normally be hidden from users by user permissions, field-level
security, or organization-wide defaults. This is particularly true for Visualforce pages.
In this case, all contact records are searched, even if the user currently logged in would not
normally have permission to view these records. The solution must use the qualifying
keywords with sharing when declaring the class:
33 of 34
Salesforce Coding Standards
The with sharing keyword directs the platform to use the security sharing permissions of
the user currently logged in, rather than granting full access to all records.
Alternatively, you may use the isAccessible, isCreateable, or isUpdateable methods of
Schema.DescribeSObjectResult to verify whether the current user has read, create, or
update access to a 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.
if (Schema.sObjectType.Contact.fields.Email.isUpdateable()) {
// Update contact phone number
}
Development Processes
• All code should be held within a Source code management system such as GIT.
• All code should be peer reviewed by a senior developer.
• All commits need comments including User Story ID and description of the work
performed.
Reference Documentation
The following is a list of links where additional information on the subjects discussed in this
document can be found:
34 of 34
Salesforce Coding Standards