Our Apex Code Convention

This document defines a set of rules and styles to follow when coding Apex in the Salesforce platform. Following these guidelines can improve the readability and traceability of the source code. This makes it easier to maintain the software.

Goal

Ensure compliance with the following Apex coding guidelines in the Salesforce platform

  • consistent,
  • easy to read and
  • Reliable code,

especially in large development teams or projects with multiple contributors.

Area of application

A code convention is a finished document that contains a comprehensive collection of guidelines. Existing code conventions from other companies can be used to create your own code convention. The guidelines from the document can be adopted in full or slightly adapted. Based on the discussions and the results of the 4-eyes principle, further guidelines can be included in the code conventions to avoid future uncertainties.

Guidelines

By analyzing 5 coding conventions from different companies, we derived our own collection of Apex coding guidelines in the Salesforce platform. Only the relevant guidelines were considered.

Naming conventions

The trailhead (https://trailhead.salesforce.com/de/content/learn/modules/success-cloud-coding-conventions) lists frequently used naming conventions. To identify these naming conventions, Salesforce sat down with some of the most experienced Success Cloud developers. The result is the “Success Cloud Naming Conventions” table, which provides an overview of the generally accepted conventions for the most common Salesforce entities.

For more information on Success Cloud naming conventions, see the Salesforce Quip document.

We have adopted the following naming guidelines from this naming convention table:

Type Naming Convention Beschreibung Beispiel
Apex Class <Namespace>_<Class Name><Optional Suffix>
  • Namespace: Is optional and is often written as an abbreviation. Is only used for classes that are exclusive to a single application/project and are certain to remain so in the long term. Not to be confused with the namespace as used in packages or dev orgs!
  • Class name: Nouns that describe the functional purpose of the class. Please do not use abbreviations.
  • Suffix: Identifies general class types such as Controller, Extension, Handler, Utilities, TriggerHandler.
SBCPT_CustomerAssessmentController

Account_SummarizeOpportunitiesExtension

Apex Test Class <Class Being Tested>_Test SBCPT_CustomerAssessmentController_Test

Account_SummarizeOpportunitiesExtensionTest

Apex Methods <Verb(s)><(optional) Noun Set> – Verbs: describe the actions performed: get, save, check etc.
– Noun phrase: describes what the verbs act on.
getParentAccount()
Apex Variables <Short yet meaningful nouns> Avoid variable names with only one letter, except for temporary variables or loop variables.. Good:

parentAccount

Bad:

pA

pAcc

Apex Constants <Capitalized words> You should describe the constant without using too many words. All letters must be capitalized. MAX_CHARACTERS

Functions

Functions should be short and concise and fulfill only one purpose. They should do one thing and do it well.

However, if you have a complex function and suspect that others will not understand what the function is about, then you should adhere to the upper limits all the more. Divide the function into several auxiliary functions with meaningful names.

Variable placement

Only place declarations at the beginning of blocks.

Try to initialize local variables where they are declared. The only reason why a variable should not be initialized where it was declared is if the initial value depends on a previously performed calculation.

Example:

function z1(){//Good
var a = 1;
var b = 2;

}
function z2(){//Bad

var a = 1;

var b = 2;

}

Choice of bracket style

We follow the style of Kernighan and Ritchie.

Example:

Kernighan and Ritchie style (Good):

functionTest(){

}

while (x == y) {
func1();
func1();
}

function1(){

}

Allman style (Bad):

functionTest()
{

}

while (x == y)
{
func1();
func1();
}

function1()
{

}

Use of optional brackets

Parentheses are used for if, else, for, do and while statements, even if the text body is empty or only contains one statement.

Example:

//Good

if(…){
exampleFunction()
}

//Bad

if(…) exampleFunction()

One instruction per line

Each instruction is followed by a line break.

Example:

//Good

function1();
function2();

//Bad

function1();function2();

Distances

Most binary and ternary operators, such as the following, must be surrounded by a space (on either side):

= + – < > * / % | & ^ <= >= == != ? :

But no space after the prefix increment & decrement for unary operators:

++ —

Example:

1.
Good:
spam(ham[1], {eggs: 2})
Bad:
spam( ham[ 1 ], { eggs: 2 } )

2.

Good:

x = 1 y = 2
long_variable = 3

Bad:

x                         =   1
y                         =   2
long_variable   =   3

3.

Good:

i = i + 1
submitted += 1
x = x*2 – 1
hypot2 = x*x + y*y
c = (a+b) * (a-b)

Bad:

i=i+1
submitted +=1
x = x * 2 – 1
hypot2 = x * x + y * y
c = (a + b) * (a – b)

4.

Good:

if( x >= 35){
y = 3 * 3;
x = (x*x) + (y / (2*y));
x++;
–y;
}

Bad:

if( x>=35){
y = 3*3;
x = (x*x)+(y/(2*y));
x ++;
— y;
}

5. Casts should be followed by a blank

Good:

byte x = (byte) aNum;
int y = (int) (cp + 5);

Bad:

byte z = (byte)varExample;

Wrapping lines

If an expression does not fit into a line, it must be converted according to the following general principles:

  • Wrap after a comma.
  • Wrap in front of an operator.
  • Upheavals at a higher level are preferable to upheavals at a lower level.
  • Align the new line at the beginning of the expression on the same level as the previous line.
  • If the above rules lead to a confusing code or code that is squeezed into the right margin, you can simply insert 8 spaces instead.

Note: Avoid lines with more than 80 characters, as they are difficult to read. In general, texts should not be longer than 70 characters.

Here are some examples of method calls:

var a = function(longExpression1, longExpression2,

longExpression3, longExpression4, longExpression5);

var b = function1(longExpression1,

function2(longExpression2, longExpression3) );

var c = long_function_name( var_one, var_two,

var_three, var_four)

var b = very_vrylong_function_name(

var_one, var_two, var_three,

var_four){

}

Below is an example of the fraction of an arithmetic expression. It is preferable because the fraction occurs outside the parenthesized expression, which is at a higher level..

longName1 = longName2 * (longName3 + longName4 – longName5)

+ 4 * longname6;

The line break for if statements should generally use the 8-space rule, as the conventional indentation (4 spaces) makes the visibility of the text body more difficult. For example:

//DON’T USE THIS INDENTATION

if ((condition1 && condition2)

|| (condition3 && condition4)

||!(condition5 && condition6)) { //BAD WRAPS

doSomethingAboutIt();//MAKES THIS LINE EASY TO MISS

}

//USE THIS INDENTATION INSTEAD

if ((condition1 && condition2)

|| (condition3 && condition4)

||!(condition5 && condition6)) {

doSomethingAboutIt();

}

Special characters

For each character that has a special escape sequence (\b\t\n\f\r\"\' and \\), this sequence is used instead of the corresponding octal (e.g. \012) or Unicode escape sequence (e.g. \u000a) is used.

Beispiel:

Good:

“Hallo Mr. \”Anton\”” => Hallo “Anton”

Bad:

“Hallo Mr. \u0022Anton\u0022” => Hallo “Anton”

For the remaining non-ASCII characters, either the actual Unicode character (e.g. ∞) or the corresponding Unicode escape (e.g. \u221e) is used. The choice depends only on what makes the code easier to read and understand.

Example:

Examples where the best variant is the first one:

String firstExample = “μs”;

String secondExample = “\u03bcs”; // “μs”

String thirdExample = “\u03bcs”; // Greek letter mu, “s”

Comments

Comments are good, but there is also a danger of commenting too much. NEVER try to explain HOW your code works in a comment: It is much better to write the code so that how it works is obvious, and it is a waste of time to explain poorly written code.

Discussions of non-trivial or non-obvious design decisions are appropriate, but avoid repeating information that is already present in (and evident from) the code. Redundant comments can easily become obsolete. In general, avoid comments that may become obsolete during the development of the code.

In general, your comments should describe WHAT your code does, not HOW. Also try to avoid comments within a function body: if the function is so complex that you need to comment parts of it separately. You can insert small comments to point out or warn about something particularly clever (or ugly). Instead, you should put the comments at the beginning of the function and explain what it does and possibly WHY it does it. For more information, see the examples in the “JavaDoc comment blocks” rule.

Note: The frequency of comments sometimes reflects poor quality code. If you feel compelled to add a comment, you should rewrite the code to make it clearer.