Best Practices For Saleforce Apex

Following are the best practices that developer should follow while doing Apex Coading:

  1. Sensitive Information in Debug

Revealing information in debug statements can help reveal potential attack vectors to an attacker. Debug statements can be invaluable for diagnosing issues in the functionality of an application, but they should not publicly disclose sensitive or detailed information (this includes passwords, keys, and stack traces as error messages, among other things).

Examples of sensitive information inside debug :

OpportunityOj =[select id, name,(select id, name from pportunityLineItems) from Opportunity where id =:tempId ];

system.debug(‘*******OpportunityOj’+OpportunityOj);

Notes:-

  • Avoid sensitive information output inside debug function/s.
  • Make a minimal use as possible with debug function/s on published Apex App.

2. CRUD/FLS EnforcementĀ 

Object (CRUD) and Field Level Security (FLS) are configured on profiles and can be used to restrict access to object types and individual fields. Force.com developers should design their applications to enforce the organization’s CRUD and FLS settings and to gracefully degrade if a user’s access has been restricted.For more information, please review the documentation for CRUD and FLS on the DeveloperForce Wiki.

Examples of CRUD operations:OpportunityOj =[select id, name,(select id, name from pportunityLineItems) from Opportunity where id =:tempId ];update OpportunityOj;

Notes:-

  • CRUD/FLS check needs to be enforced before doing a DML, Please review all you class files and add the following check before doing DML operations or accessing data.
  • You should also need to perform check before querying data using a select statement.
  • Use the isAccessible() check before accessing data (for example performing a query)
  • Use the isUpdateable() check before updating data.
  • Use the isCreateable() before inserting data.
  • Use the isDeletable() before deleting data.

3. Sharing Violation

The Force.com platform makes extensive use of data sharing rules. Each object can have unique permissions for which users and profiles can read, create, edit, and delete. These restrictions are enforced when using all standard controllers. When using a custom Apex class, the built-in profile permissions, and field-level security restrictions are not respected during execution. The default behavior is that an apex class has the ability to read and update all data with 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 profile-based permissions, field-level security, or organization-wide defaults. This is particularly true for Visualforce pages. Classes should explicitly declare with sharing when possible.

Ā  Ā  Ā  Ā  Ā 4. Declaration of Constant value

All constants value which is used in the apex/visual force page should be declared on the top of the page. That declared constant should be used in the page.

Example of declaration of constant :

public with sharing class OpportunityExtention {Ā  Ā  public void CheckOpportunityStatus () {Ā  Ā  Ā  Ā  If (Opportunity.Status == ā€˜Closedā€™){Ā  Ā  Ā  Ā  Ā  Ā // Do somethingĀ  Ā  Ā  }Ā  Ā }}

Solution:-public with sharing class OpportunityExtention {private static final String CLOSED_OPPORTUNITY = ā€˜Closedā€™;public void CheckOpportunityStatus () {If (Opportunity.Status == CLOSED_OPPORTUNITY){// Do something}}}

5. Commenting Practice

Commenting should be proper throughout the application. Below is some commenting best practice is defined.

For Class :

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

** Module Name Ā Ā : Module Name

** Description Ā Ā : Description for class.

** Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā if multiline description.

**

** Organization Ā : Organization Name

**

** Revision History:-

** Version Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Date Author Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Description of Action

** 1.0 Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā 12/12/16 Developer1(Algoworks)

** 1.1 Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā 12/14/16 Developer2(Algoworks)

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

public with sharing class OpportunityExtention {

// Do something

}

For Method :

/**

* Full Description of method

*/

public void CheckOpportunityStatus () {

// Do something

}

For Inline :

// Inline description in any line

6. Use of CamelcasingAll Class name, Method name and Properties should be declared in Camelcase. Class name should be start from Capital letter. Method name and Properties name should be start from small letter. Rest words of Class, Methods and Properties should be start with Capital letter in all names.

Example of use of Camelcasing :

For Class :

public with sharing class OpportunityExtention {

//Do Something

}

For Method :

public with sharing class OpportunityExtention {

public void firstMethod () {

If (Opportunity.Status == CLOSED_OPPORTUNITY){

// Do something

}

}

}

For Properties :

public with sharing class OpportunityExtention {

public String opportunityStatus {get; set;}

}

7. Repeated code

All Repeated code should be in a different function and use them instead of repetition of code.

Example of repeated code :

public with sharing class OpportunityExtention {

private static final String CLOSED_OPPORTUNITY = ā€˜Closedā€™;

private static final String OPEN_OPPORTUNITY = ā€˜Openā€™;

public void Method () {

If (Opportunity.Status == CLOSED_OPPORTUNITY){

// Do something

}

If (Opportunity.Status == OPEN_OPPORTUNITY){

// Do something

}

}

}

Solution :

public with sharing class OpportunityExtention {

private static final String CLOSED_OPPORTUNITY = ā€˜Closedā€™;

private static final String OPEN_OPPORTUNITY = ā€˜Openā€™;

public void Method () {

ResolveRepeatedCode (opprtunity, CLOSED_OPPORTUNITY);

ResolveRepeatedCode (opprtunity, OPEN_OPPORTUNITY);

}

Private void ResolveRepeatedCode (Opprtunity opprtunity, String Status) {

If (opprtunity.Status == Status){

// Do something

}

}

}

8. External Resources in VF Page

<script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js” type=”text/JavaScript” />

<script src=”https://code.jquery.com/jquery-1.10.2.js” ></script>

<script src=”https://code.jquery.com/ui/1.11.1/jquery-ui.js” ></script>

Notes :-

All resources for VF page should be included inside the package statically and not referenced from an external source.

e.g. https://code.jquery.com/jquery-1.10.2.js should be within a relative path and included statically “/jquery-1.10.2.js”.

9. External Resources in Objects

Code:

In “Buttons, Links, and Actions” (View):

$j(‘head’).append(‘<link rel=”stylesheet” href= “https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css”

type=”text/css”/>’);

Notes :-

All resources should be included inside the package statically and not referenced from an external source.

e.g. “https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css” should be within a relative path and included statically “/jquery-ui.css”.

10. Unused CodeUnused code :

/* JSONGenerator gen = JSON.createGenerator(true);

gen.writeStartObject();

gen.writeFieldName(‘charge’);

gen.writeStartObject();

String generate = gen.getAsString();*/

Notes :-

Please remove unused code from your solution.

11. Stored XSS Vulnerability

Cross-Site Scripting attacks are a type of injection problem, in which malicious scripts are injected into the otherwise benign and trusted web sites. Cross-site scripting (XSS) attacks occur when an attacker uses a web application to send malicious code, generally in the form of a browser side script, to a different end user. Flaws that allow these attacks to succeed are quite widespread and occur anywhere a web application uses input from a user in the output it generates without validating or encoding it.An attacker can use XSS to send a malicious script to an unsuspecting user. The end user’s browser has no way to know that the script should not be trusted, and will execute the script. Because it thinks the script came from a trusted source, the malicious script can access any cookies, session tokens, or other sensitive information retained by your browser and used with that site. These scripts can even rewrite the content of the HTML page.Stored XSS attacks are persistent and occur as a result of malicious input being stored by the web application and later presented to users.Location in Code :-

<script type=”text/javascript”>

function popupwindow2(){

window.open(‘/apex/ChangePlan?id={!Opportunity.Id}&subdomain={!Opportunity.Chargify_SubDomain__c}

‘,’Popup1′,’height=400,width=500,left=400,top=200,scrollbars=yes,toolbar=no,status=no’);

}

</script>

Notes :-

  • No escaping performed on Visual force pages specially when displaying data inside script tags , you should encode displayed data
  • In the example above the “raw” html data received in the JSON response is not escaped in the “subdomain” parameter and result in a XSS in the native application visualforce page.
  • The platform provides the following VisualForce encoding functions:
    • JSENCODE — performs string encoding within a Javascript String context
    • HTMLENCODE — encodes all characters with the appropriate HTML character references so as to avoid interpretation of characters as markup.
    • URLENCODE — performs URI encoding (% style encoding) within a URL component context
    • JSINHTMLENCODE — a convenience method that is equivalent to the composition of HTMLENCODE(JSENCODE(x))

Solution :-

<script type=”text/javascript”>

function popupwindow2(){

window.open(‘/apex/ChangePlan?id={!Opportunity.Id}&subdomain={!JSENCODE(Opportunity.Chargify_SubDomain__c)}

‘,’Popup1′,’height=400,width=500,left=400,top=200,scrollbars=yes,toolbar=no,status=no’);

}

</script>

12. Insecure Software VersionWhen new vulnerabilities are discovered in software, it is important to apply patches and update to a version of the software for which the vulnerability is fixed. Attackers can create attacks for disclosed vulnerabilities very quickly, so security patches should be deployed as soon as they are available.

Jquery-ui-1.11.2Jquery-1.11.3.js

Notes :-

jquery-1.11.3.js:

– jquery 1.11.3 has known vulnerabilities: 3rd party CORS request may execute; https://github.com/jquery/jquery/issues/2432

http://blog.jquery.com/2016/01/08/jquery-2-2-and-1-12-released//jquery-ui-1.11.2/jquery.min.js:

– jquery 1.11.2 has known vulnerabilities: 3rd party CORS request may execute; https://github.com/jquery/jquery/issues/2432

jQuery 2.2 and 1.12 Released

Fix :-

Please upgrade jquery libraries to most recent/secure version.

Happpy Salesforce šŸ™‚