coding standards document · pdf file recommends following standards for naming, that is,...

19
Salesforce.com Coding Standards Document Version 1.1 Salesforce.com Professional Services December 30, 2013

Upload: phungngoc

Post on 26-Mar-2018

216 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Coding Standards Document · PDF file  recommends following standards for naming, that is, classes start with a capital letter, methods start with a lowercase verb,

Salesforce.com

Coding Standards Document

Version 1.1

Salesforce.com Professional Services

December 30, 2013

Page 2: Coding Standards Document · PDF file  recommends following standards for naming, that is, classes start with a capital letter, methods start with a lowercase verb,

Table of Contents

Contents

1. ACRONYMS AND DEFINITIONS .................................................................................................................... 4

2. OVERVIEW...................................................................................................................................................... 5

3. APEX CLASS .................................................................................................................................................... 6

3.1. CLASS LAYOUT ........................................................................................................................................... 7 3.2. CLASS VARIABLES ....................................................................................................................................... 8 3.3. METHODS ................................................................................................................................................. 8 3.4. LOGICAL STATEMENTS ................................................................................................................................ 9 3.5. DEBUG LOGS ...........................................................................................................................................10 3.6. STATIC VALUES ........................................................................................................................................10 3.7. GENERAL CONVENTIONS ...........................................................................................................................10 3.8. INDENTATION ..........................................................................................................................................11 3.9. CODE COMMENTS ....................................................................................................................................12

3.9.1. Block Comments .........................................................................................................................12 3.9.2. Single Line Comment ..................................................................................................................12 3.9.3. Trailing Comment .......................................................................................................................12 3.9.4. End of Line Comment .................................................................................................................12

3.10. EXCEPTION HANDLING CONVENTIONS ....................................................................................................13 3.10.1. try-catch Block ............................................................................................................................13 3.10.2. Exception Logging Methodology ..............................................................................................14

3.11. API DEVELOPMENT..............................................................................................................................14 3.12. TESTING AND CODE COVERAGE .............................................................................................................14

4. VISUALFORCE PAGES/ COMPONENTS ......................................................................................................16

4.1. PAGE LAYOUT ..........................................................................................................................................16 4.2. GENERAL CONVENTION.............................................................................................................................17

5. TRIGGERS .....................................................................................................................................................18

6. REFERENCES .................................................................................................................................................19

Page 3: Coding Standards Document · PDF file  recommends following standards for naming, that is, classes start with a capital letter, methods start with a lowercase verb,

Revision History and Approvers Date Version Description Author 11/09/2009 1.0 Initial Document Suchin Rengan 12/30/2013 1.1 Updated to Winter 14 Aaron Levensailor

Page 4: Coding Standards Document · PDF file  recommends following standards for naming, that is, classes start with a capital letter, methods start with a lowercase verb,

1. Acronyms and Definitions

Acronym Definition Apex Server-side scripting for Salesforce AJAX Client Scripting for Salesforce API Application Program Interface DB Database Dev Development Environment SFDC Salesforce.com (dot com) WSDL Web-Service Definition Language XML Extensible Markup Language VF VisualForce – Salesforce scripting framework OOTB Out Of The Box UI User Interface

Page 5: Coding Standards Document · PDF file  recommends following standards for naming, that is, classes start with a capital letter, methods start with a lowercase verb,

2. Overview

This document is intended for developers who will be developing code in a Salesforce.com org. It should be noted that these standards are not strictly enforced, rather a means to provide code consistency and adherence to Salesforce.com best practices. It should rather be used as a guide and reference purposes only. Enforcing standards have the following benefits:

Easily maintainable code Delivery consistency Adherence to best practices that results in improved code performance

Page 6: Coding Standards Document · PDF file  recommends following standards for naming, that is, classes start with a capital letter, methods start with a lowercase verb,

3. Apex Class

Salesforce.com recommends following 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. Class Name: Name can consist of alphanumeric characters. It should be unique, beginning with an uppercase letter. It should not contain underscores and spaces. The words should be concatenated with Initial uppercase. Example: “ConfigureOpportunity”

Page 7: Coding Standards Document · PDF file  recommends following standards for naming, that is, classes start with a capital letter, methods start with a lowercase verb,

3.1. Class Layout

/**********************************************************************

Name: ConfigureOpportunity()

Copyright © 2009 ABC Company Inc.

======================================================

======================================================

Purpose:

-------

======================================================

======================================================

History

-------

VERSION AUTHOR DATE DETAIL FEATURES/CSR/TTP

1.0 - Name 03/04/2009 INITIAL DEVELOPMENT CSR:

2.0 - Name 03/23/2009 UDAC WIRE FRAME CHANGES TTP:

***********************************************************************/

<access> class <name>

{

//Static Block

{

//Static variable

//Static Methods

}

//Non-Static Variables

..

// Constructors

..

// getter & setter methods

..

// Action Methods

..

// Logical Methods

// Inner Classes and Functions

}

Page 8: Coding Standards Document · PDF file  recommends following standards for naming, that is, classes start with a capital letter, methods start with a lowercase verb,

3.2. Class Variables

1. Variables name should be meaningful. Abbreviations in names should be avoided. Like: computeAverage(); // NOT: compAvg();

2. Negated Boolean variable names must be avoided.

boolean isError; // NOT: isNoError

3. Avoid the use of Static variables where possible

4. SFDC Keywords cannot be used as Class variables

3.3. Methods

1. Method should have meaningful names starting with lowercase and following words should have initial uppercases.

2. Methods should have a try-catch-finally block to handle possible exceptions. The try-catch block should appear at logical places where you are sure of Exception nature and its handling.

3. Methods should have Debug statements in the beginning and at the end or before the return. This should also include Input and Output parameters to help debugging the code (as shown in the example below)

4. Methods should have block comments to capture the details in format shown below:

public class ConfigureProducts {

..

..

/******************************************************************* Purpose: Detailed description of the method

Parameters: [optional]

Returns: [optional]

Throws [Exceptions]: [optional]

********************************************************************/ public String addUDAC(param1, param2) {

system.debug(‘Entering <Method Name>: ‘+ <I/P parameters>);

system.debug(‘Exiting <Method Name>: ‘+ <return value if

any>);

return ..;

}

}

1. 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. Example:

For the instance variable "customerID", the getter and setter method names can have following formats:

I. public string customerID{get; set;}

Page 9: Coding Standards Document · PDF file  recommends following standards for naming, that is, classes start with a capital letter, methods start with a lowercase verb,

II. public string customerID; // Variable declaration

section

public string getCustomerID() { //Get method definition

return <string>;

}

public string setCustomerID() { //set method definition

return <string>;

}

3.4. Logical Statements

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

}

The SOQL for loop: for (variable : [soql_query]) {

code_block

}

OR

for (variable_list : [soql_query]) {

code_block

}

While Loop:

while (!done) {

doSomething();

done = moreToDo();

}

if-else:

if (condition) {

statements;

}

if (condition) {

statements;

} else {

statements;

}

Page 10: Coding Standards Document · PDF file  recommends following standards for naming, that is, classes start with a capital letter, methods start with a lowercase verb,

if (condition) {

statements;

} else if (condition) {

statements;

} else {

statements;

}

3.5. 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 recorded when the user reaches that limit. Each debug log will contain up to 2mb of data; older log lines wi ll 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.

3.6. Static Values

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.

3.7. General Conventions

1. Do not use S-CONTROLs

2. Declare all class variables at the beginning of each class.

3. All instance variables must be declared either private or protected.

4. A class should have limited public variables except 'final' or 'static final'. Try to avoid public variables where possible

5. To convert a primitive type to String use String.valueOf() instead of var + ""

6. Avoid any type of hard coding in the code. Use Custom Labels, Custom Settings or static Apex Classes to drive any configuration related values

7. 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

8. Do not instantiate any object before you actually need it. Specifically, do not instantiate objects in variable declarations outside the try block.

9. All constants should have uppercase names, with logical sections of the name separated by underscores.

10. Local variables should not have the same name as instance variables. In general, variables in a nested scope should not have the same name as variables in outer scopes.

Page 11: Coding Standards Document · PDF file  recommends following standards for naming, that is, classes start with a capital letter, methods start with a lowercase verb,

11. 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.

12. 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.

3.8. Indentation

Use Tabs (4 spaces) for indentation. Set you editor tab to 4 spaces. Line Length Avoid lines longer than 80 characters, since they’re not handled well by many terminals and tools. Split lines occurs 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:

Break after a comma. Break after an operator.

Align the new line with the beginning of the expression on the previous line. Example#1:

//DON'T USE THIS INDENTATION

longName1 = longName2 * (longName3 + longName4

-longName5) + 4 * longname6;

//USE THIS INDENTATION INSTEAD

longName1 = longName2 * (longName3 + longName4 - longName5)

+ 4 * longname6;

Example#2:

//DON'T USE THIS INDENTATION

if ((condition1 && condition2)

|| (condition3 && condition4)

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

doSomethingAboutIt(); } //MAKE THIS LINE EASY TO MISS

//USE THIS INDENTATION INSTEAD

if ((condition1 && condition2)

|| (condition3 && condition4)

||!(condition5 && condition6)) {

doSomethingAboutIt();

}

//OR USE THIS

if ((condition1 && condition2) || (condition3 && condition4)

||!(condition5 && condition6)) {

doSomethingAboutIt();

}

Page 12: Coding Standards Document · PDF file  recommends following standards for naming, that is, classes start with a capital letter, methods start with a lowercase verb,

Example#3:

//USE THIS INDENTATION

someMethodCall(longExpression1, longExpression2, longExpression3,

longExpression4, longExpression5);

3.9. Code Comments

3.9.1. Block Comments

Block comments are used to provide descriptions of files, methods, data structures and algorithms. Block comments inside a function or method should be indented to the same level as the code they describe. Block comment for Files: Section 3.1 Block comment for Methods: Section 3.3 Block comment for data structures and algorithms: Example:

/* Start Version: X.X

* Block comments with details of changes

* ..

* ..

*/

..

..

/* End Version: X.X */

3.9.2. Single Line Comment

Short comments can appear on a single line indented to the level of the code that follows. Example:

if (condition) {

// Handle the condition.

...

}

3.9.3. Trailing Comment

Very short comments can appear on the same line as the code they describe, but should be shifted far enough to separate them from the statements. Example:

if (a == 2) {

return TRUE; // special case

} else {

return isPrime(a); // works only for odd a

}

3.9.4. End of Line Comment

The // comment delimiter can comment out a complete line or only a partial line. It can be used

in consecutive multiple lines for commenting out sections of code. Examples of all three styles follow:

Page 13: Coding Standards Document · PDF file  recommends following standards for naming, that is, classes start with a capital letter, methods start with a lowercase verb,

Example: if (foo > 1) {

// Do a double-flip.

...

}

else {

return false; // Explain why here.

}

/* Start Version: X.X

* Here is a block comment.

if (bar > 1) {

// Do a triple-flip.

...

}

else {

return false;

}

*/

/* End Version: X.X */

3.10. Exception Handling Conventions

Please refer to “Salesforce Apex Language reference” for details on Exception types, methods and classes as listed below:

1. Exception Class

2. Common Exception Methods

3. DMLException and EmailException Methods

4. Bulk DML Exception handling

5. Exception Statements

I. Throw Statements

II. Try-Catch-Finally Statements

6. Trigger Exceptions

7. Handling Uncaught Exceptions

3.10.1. try-catch Block

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 method name, line number and type of error. It also displays Error message on the UI, but that may not be meaningful for the end user. The email message helps track the error while debugging.

Page 14: Coding Standards Document · PDF file  recommends following standards for naming, that is, classes start with a capital letter, methods start with a lowercase verb,

3.10.2. Exception Logging Methodology

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:

1. Store error messages and related information in a Custom object. The custom object will store severity, error type, user and other related details

2. Use Workflows to send email notification whenever a user encounters error based on the error severity

3. Cleanup or Archive error data

4. have custom reports created to generate errors based on status and severity

3.11. API Development

To develop Web service client applications, it is strongly recommended that you use Salesforce.com Sandbox Edition, which is an exact replica of your Salesforce.com deployment, including all customization and data. For more information, see https://help.salesforce.com/apex/HTViewHelpDoc?id=create_test_instance.htm. Standard Compliance: The API is implemented to comply with the following specifications: Standard Name Website Simple Object Access Protocol (SOAP) 1.1 http://www.w3.org/TR/2000/NOTE-SOAP-

20000508/ Web Service Description Language (WSDL) 1.1

http://www.w3.org/TR/2001/NOTE-wsdl-20010315

WS-I Basic Profile 1.1 http://www.ws-i.org/Profiles/BasicProfile-1.1-2004-08-24.html

API Support & End-of-Life Salesforce.com is committed to supporting each API version for a minimum of three years from the date of first release. In order to mature and improve the quality and performance of the API, versions that are more than three years old may cease to be supported.

3.12. Testing and Code Coverage

To facilitate the development of robust, error-free code, Apex encourages 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.

Page 15: Coding Standards Document · PDF file  recommends following standards for naming, that is, classes start with a capital letter, methods start with a lowercase verb,

Example: @IsTest

public class myClass {

static testMethod void myTest() {

code_block

}

}

Best Practices for Writing Unit Tests:

1. Cover as many lines of code as possible

I. You must have at least 75% of your Apex scripts covered by unit tests to deploy your scripts to production environments. In addition, all triggers should have some test coverage.

II. Salesforce recommends that you have 100% of your scripts covered by unit tests, where possible.

III. Calls to System.debug are not counted as part of Apex code coverage in unit tests.

2. In the case of conditional logic (including ternary operators), execute each branch of code logic.

3. Make calls to methods using both valid and invalid inputs.

4. Complete successfully without throwing any exceptions, unless those errors are expected and caught in a try…catch block.

5. Always handle all exceptions that are caught, instead of merely catching the exceptions.

6. Use System.assert methods to prove that code behaves properly.

7. Use the runAs method to test your application in different user contexts.

8. Test methods should be encapsulated in a class marked with @IsTest and clearly named as a peer to the class under test (i.e., named TargetClassTest).

9. Use the isTest annotation. Classes defined with the isTest annotation do not count

against your organization limit of 3 MB for all Apex scripts.

10. Exercise bulk trigger functionality—use at least 20 records in your tests.

11. 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.

12. Test the classes in your application individually. Never test your entire application in a single test.

13. User records are not covered by test methods.

14. There should always be separate methods for parsing the response of a webservice call. This way it will help in writing test methods for code coverage and debugging the code when required.

15. Create the necessary data in test classes. Tests should not rely on data in a particular organization.

Page 16: Coding Standards Document · PDF file  recommends following standards for naming, that is, classes start with a capital letter, methods start with a lowercase verb,

4. Visualforce Pages/ Components

Label: The Label name should start with uppercase letter and has to be short and meaningful. The words in the

name should be separated by spaces.

Example: “Configure Opportunity”

Name: Name can consist of alphanumeric characters. It should be unique, beginning with an uppercase letter. It

should not contain underscores and spaces. The words should be concatenated with Initial uppercase.

Example: “ConfigureOpportunity”

Description: Give meaningful description of the visualforce page.

4.1. Page Layout

<apex:page controller="DependentObjects" id="UseCaseDisplay" label="FeatureCategoryReport" >

<!--====================================================-->

<!--Name: ConfigureOpportunity() -->

<!--Copyright notice: -->

<!--====================================================-->

<!--====================================================-->

<!-- Purpose: -->

<!--------- -->

<!--====================================================-->

<!--====================================================-->

<!-- History -->

<!-- ------- -->

<!-- VERSION AUTHOR DATE DETAIL RELEASE/CSR -->

<!-- 1.0 - Team/Name 03/04/2009 INITIAL DEVELOPMENT -->

<!-- 2.0 - Team/Name 03/24/2009 UDAC WIRE FRAME CHANGES -->

<!--====================================================-->

<apex:form>

<apex:pageBlock title="Feature Selection" mode="edit"

id="thePageBlock">

<apex:pageBlockSection columns="1">

<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>

Page 17: Coding Standards Document · PDF file  recommends following standards for naming, that is, classes start with a capital letter, methods start with a lowercase verb,

</apex:pageBlock>

</apex:form>

</apex:page>

4.2. General Convention

1. Make sure that each Page items(all visualforce tags) has ID and the IDs should be unique 2. Pay attention to the comments and remarks and put them in legible form before every Page

item 3. 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}

4. 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.

5. The alignments have to be properly maintained with a tab of 4 spaces 6. It is recommended to have partial rendering of a page item then a full page 7. 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.

Page 18: Coding Standards Document · PDF file  recommends following standards for naming, that is, classes start with a capital letter, methods start with a lowercase verb,

5. Triggers

Name: 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. The

words should be concatenated w ith Initial uppercase.

Example: “ProposalUpdateStatus”

1. Create a single trigger per object. 2. User-defined methods in a trigger cannot be declared as static. 3. 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. 4. You can only set five savepoints in all contexts 5. 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.

Page 19: Coding Standards Document · PDF file  recommends following standards for naming, that is, classes start with a capital letter, methods start with a lowercase verb,

6. References

1. Salesforce Apex Language Reference Winter ’14. 2. Salesforce: User Guide, Salesforce Winter ’14. 3. Salesforce help & support from SFDC.com developer's site

4. Salesforce.com Cookbook