Thursday 7 August 2014

Object-Oriented Programming in Apex

1.      Classes
2.      Properties
3.      Encapsulation
4.      Polymorphism and Inheritance
5.      Virtual Class
6.      Abstract class
7.      Interfaces 

Classes

  • A class is a template or blueprint from which objects are created.
  • They consist of methods and attributes
  • Are stored with the version of API that is used to compile it
  • May contain other classes, known as inner classes (but these can only be one level deep)
  • Even though Apex code is not case sensitive, it is recommended that you follow the Java naming convention
  • Static methods and attributes can only be declared in a top-level class definition
  • To create new exception classes, the Exception class must be extended
  • Classes can be enabled or disabled for profiles.
Ways to Create Classes
  • Through the UI:
    • Go to Setup -> Develop and Apex Classes.
    • Click “New” or “Generate from WSDL”
    • Enter code or upload a WSDL
  • Through a Force.com IDE project:
    • Right-click the src folder and click New -> Apex Class (this is the recommended way)
Class Syntax:
private | public | global
[virtual  | abstract | with sharing | without sharing | (none)]
Class ClassName [implements InterfaceNameList | (none)] [extends ClassOrInterfaceName | (none}] {
// The body of the class
}
Example
public class myOuterClass {
            // Additional myOuterClass code here
            class myInnerClass {
                                    // myInnerClass code here
            }
}

  • If global, the class is accessible everywhere. This must be used with the webService keyword. All methods, attributes and inner classes that are global must be within a global class
  • If public, the class is visible across the application, org or namespace that comprises the class.
  • If private is used for an inner class, the inner class is only accessible to the outer class. The default for inner classes is private.
  • Top level or outer classes must have either a global or public keyword.
  • A class can implement multiple interfaces, but it can only extend once class
  • A class can cast as a superclass and verify an objects class using the instanceof keyword
  • You can implement and extend classes using the keywords, virtual, abstract and extends
    • Virtual declares that the class allows extensions and overrides, Classes that are virtual cannot be global.
    • Abstract declares that the class contains abstract methods and can be extended. These classes just have a method signature and do not have code. You cannot instantiate an object of an abstract class until some other class extends it.
    • The Extends keyword declares that the class is a subclass. The “super” keyword can be used to invoke constructors and methods from the parent class.
  • All Apex code executes in the system mode and ignores all CRUD, field-level security and record sharing level privileges. You use with and without sharing keywords to implement sharing. By default a class will run in the without sharing mode.
    • With sharing – This means that when performing DML operations, the user can only update records to which he or she has edit level access
    • Without Sharing – This ensures that sharing model access is ignored and is referred to a running in system mode.
  • Interfaces are classes that only include the method signature. The methods are not implemented in the interfaces. Apex supports both top-level and inner interfaces
  • Avoid using standard object names for class names. Doing so causes unexpected results

Properties/ Attributes Syntax


Properties are the shortened form of a method that has access to static and instance variable.
modifiers dataType attributeName initialization;
For example:
public static final Integer MAX_AMOUNT = 200;
 private Integer cost;
public Integer getcost() { return cost; }
public void setcost(Integer cost) { this.cost=cost; }
  // Variable as Property
 public Integer cost { get { return cost; }  set { this.cost= cost;}}
  //Variable as Automatic Property
public Integer cost { get; set; }

//read-only and write - only Property
public Integer readOnly { get; private set;}
public Integer wrtieOnly { private get; set;}

 Methods Syntax:

Modifiers returnDataType methodName (inputParameterList) {
// method code
}
For example:
Public Integer getInt() {
Return myInt;
}
 Method and Attribute Access Modifiers
  • Private – Default access modifier, but is not available for top-level classes. It implies that the attribute or method is only available in the class where it is defined.
  • Protected – Available only to inner classes
  • Public – Can be used by an apex code in the application, org or namespace
  • Global – Accessible by all Apex everywhere. Note that Apex code cannot be shared between orgs, with the exception of Web Services, which are accessible to everyone.
Static Methods and Attributes
  • Static methods are accessed through the class itself and do not depend on an instance of a class
  • Static attributes are used to store data that is used within the class. They can be used to prevent recursive logic by setting flags.
Constants
  • Assign a value to a constant only once either at declaration or initialization
  • Define a constant using both the static and final keywords.
Instantiating Objects
  • Allows you to work with methods and attributes that are not defined as static
  • After instantiating, you can refer to methods and attributes using the dot notation. For example:
TestObject myObject1 = new TextObject();
myObject1.myMethod();
  • A constructor is a special method used to create an object of a class. It has the same name as the class and is the first method invoked in the class. It does not have an explicit return type and is available by default in each class as invisible and without parameters. It can be overloaded by defining multiple constructors with different parameters.
The “this” Keyword
  • With dot Notation – Used to represent the current instance of the class and can call methods or set attributes that are public or are available.
  • With Constructors – Developers can do constructor chaining by using the this keyword, but the this keyword must be the first statement in the constructor.
Apex System-Delivered Classes
  • System Class – Is a static class that contains only static methods. Includes the following:
    • Debug()
    • Now()
    • Today()
    • Assert()
    • AssertEquals()
    • AssertNotEquals()
  • UserInfo Class – Mostly getter methods used to get details. For example:
    • getUserId()
    • getUserName()
    • getUserRoleId()
    • getFirstName()
    • getLocale()
    • getLanguage()
Apex Workflow and Approval Processing
  • Apex process classes are used to submit workflow requests and process the results of those requests. The three classes provided are:
    • ProcessRequest – Used to process the results from a workflow process
    • ProcessSubmitRequest – Used to submit a workflow item for approval
    • ProcessWorkItemRequest – Used to process an item after it is submitted

Encapsulation

When a class is defined it becomes a new data type in Apex
public class MyClass()
{
    MyClass c  = new MyClass();
    List<MyClasss> myList = new List<MyClass>();
    myList.add(c);
}

Monday 12 May 2014

We can check map key using "CONTAINS" Formula method on Visualforce page

Sample Code

VisualForce Page

<apex:page standardController="Account" recordSetVar="account" extensions="MapkeyExample">
    <apex:pageBlock>
        <apex:pageBlockTable value="{!Account}" var="acc">
            <apex:column headerValue="Account Name">
                <apex:outputLabel value="{!acc.name}"></apex:outputLabel>
                <apex:pageBlockTable rendered="{!IF(CONTAINS(ChkMapKey,acc.name),true,false)}" value="{!accMap[acc.name]}" var="ss">\
                    <apex:column headerValue="Child Map value" value="{!ss}" />
                </Apex:pageBlockTable>
            </apex:column>
        </Apex:pageBlockTable>
    </apex:pageBlock>
</apex:page>

Apex Class

public class MapkeyExample
{
    public string ChkMapKey{get;set;}
    public map < string, string > accMap{get;set;}
    public MapkeyExample(ApexPages.StandardSetController controller)
    {
        accMap = new map < string, string >{'test' => '1', 'test account' => '2', 'C' => '3', 'D' => '4', 'E' => '5', 'F' => '6'};
        ChkMapKey = string.valueof(accMap.keyset()).replace('{', '').replace('{', '');
    }
}

In above code i have created following things:
1. Test Account
2. ChkMapKey String propeerty
3. accMap Map.

Monday 31 March 2014

SFDC Coding Best Practice



While developing in the Salesforce cloud we ask that you follow some simple standards to help keep our organization nice and tidy. Doing so is beneficial to everyone as it will make it easier to identify which metadata goes to which apps and which functional group.
i)                General Practices

ii)              Apex Class Naming Convention

iii)             Apex Page Naming Convention (VisualForce)

iv)            SObject Naming Convention

v)              Permission Sets

vi)            Test Method

1.1   general practice

­        Description is always needed for Object, Field,Tab, Application, Workflow Rule and ALL OTHERS. If there is a description field, that's mean description is needed.

­        Always use standard functionality provided by Salesforce. Use codes only if standard functionality is not able to achieve the requirement.

­        Header and Change history is always needed for all codes. This is to help others to understand what is the code doing and what changes had been made. Always start with Header, before you start code. Always update change history , before you start change.

­        NO SQL in For Loop. SOQL 101 is the common error, due to the process had run more than 100 queries. One of the common mistakes is having SOQL in For Loop. We are restricted no SOQL in For Loop in any condition. Even though you are 101% confidence and guarantee only 1 record to be process.

­        Never hardcoded record ID. Record can be changed or deleted by someone without your notice.

­        Avoid SQL injection.

a) End user can inject code into the SOQL query causing data to be returned to be modified.

APEX

     use the String.escapeSingleQuotes method to escape the value so the variable cannot modify the SOQL command. Example:


String query = ‘select id from object where field = \’’ + String.escapeSingleQuotes(value) + ‘\’’;

b) End user can inject javascript code if developer uses controller or object variable

inside javascript code.

Javascript

    Developer should use the JSENCODE function. Example:

var x = ‘{!JSENCODE(somecontrollervariable)}’;


1.2 Apex Class Naming Convention


Naming your Apex class is as important as writing clean code. For Apex classes we ask that you follow the below standards.

[GROUP]_[APP]_[ClassName]_[Type (Ctrl,Controller,Ext,Extension ­if applicable)]_[Test (if applicable)]

Note: Try to avoid shortening the application name if possible. Classes can contain up to 40 characters in the name.

Examples:

CRMIT_ReleaseManagement_MetaFinder_Ctrl

This class is owned by the CRM IT team and is a part of the Release Management application. This specific class is part of a mini utility called MetaFinder and is a controller class to a VisualForce page.

CRMIT_ReleaseManagement_MetaFinder_Test

This class is owned by the CRM IT team and is a part of the Release Management application. This specific class is part of a mini utility called MetaFinder and is the test coverage code to the previously mentioned controller class.

Note: The Ctrl was dropped from this due to expanding beyond the 40 character limit for ApexClass names.

Global_DataTableExt

This class is a global class used by the DataTable global utility.

1.3 Apex Page Naming Convention (VisualForce)


Along with naming your Apex classes it helps to name your pages with the same format to keep them in line with the rest of the application. Doing so makes it easier to identify a page's controller and extension classes easily.

[GROUP]_[APP]_[PageName]_[VF (optional)]

Note: Try to avoid shortening the application name if possible. Pages can contain up to 40 characters in the name.

Examples:

CRMIT_RM_MetaFinder

This page is owned by the CRM IT team and is a part of the Release Management application. The page is a portion of the application called MetaFinder.


Global_DataTale_Export_VF

This page is a globally used page and is provides data table functionality. This page offers exporting and is appended with a VF to indicate VisualForce. The VF is not necessary but some developers opt to do this. Being at the end it doesn't alter the identity of the page any.

Exceptions to this standard:

There are some exceptions to this rule surrounding external usage applications hosted in Sites such as Where To Buy and Web­to­Case (and chat). Pages such as these with a large user base can use more localized names that are user friendly such as ChatLaunch, ChatHome, CreateSupportCase.


1.4 SObject Naming Convention


Naming a SObject follows the same basic structure as Apex and VisualForce pages.

[GROUP]_[APP]_[ObjectName]

Note: Try to avoid shortening the application name if possible. SObjects can contain up to 40 characters in the name.

Additionally we ask that all objects labels contain the application prefix. For example the Site Inspection application which uses the prefix SIA will have an object labeled SIA Frequency. This allows multiple apps to use the same named object without causing confusion for users in the tab list, and developers and admins in the profile and object lists.

LEGAL_ROLF_Tag__c

Examples:

This object is owned by the Legal team and is a portion of their case threading system. This particular object is used to store a custom tag data for the threads.

1.5 Permission Sets

Permission sets should be named with the below standard: [GROUP] [APP] [FUNCTION]

Permission sets should be leveraged in lieu of individual profiles.

Example: Sales SSRA CRUD ­ This name is for the Sales department supporting the Secondary Sales Rep Assignment and provides CRUD access to their application objects.

 1.6 test method

All Apex Class and Apex Trigger must having Test Method, to run unit test on the class / trigger.

Test Method cannot embedded in the actual running class. All Test Method class must having @isTest annotation. No hardcoded ID use in TestMethod.

Always create your own test data for testmethod, instead query data from instance.


Minimum code coverage for APEX Class and Trigger is 75%.

All classes and triggers must meet minimum code coverage 75%