Salesforce: Apex Programming Language

Lesson 1: Basics of Apex Programming Language

Vaibhav Vaid
7 min readApr 3, 2021

What is Apex Programming Language?

Apex is a strongly typed (variables need to be defined before they are used), case insensitive, object oriented language used by Salesforce for writing custom business logic on their platform. Apex is saved, executed, compiled on force.com platform, and though code is not saved on client’s side.

Do you really need to code in Salesforce?

Coding is Salesforce is not a compulsory thing to do. Salesforce provides many useful declarative tools like Process Builders, flows etc., that can be used to execute simple and complex business logic.

So if Salesforce provides pre-built declarative tools, Why do we need to code?

When a business process is too complex to be implemented by using simple declarative tools, then only a developer should code. Few of the use cases of Apex are: Creating a custom validation on standard object, which cannot be set by standard validation rule, Creating a web service that can integrate Salesforce with other applications, Executing custom business logic when DML operation is performed, or setting up an email service where header, content or it’s attachments needs to be added using Apex.

Where to write the Apex?

Salesforce allows multiple environments where Apex code could be written and moved to Salesforce environment.

Within Salesforce Apex could be written using:

  • Developer Console:
Click on gear icon and Select Developer Console. A new window will open from where you can click on File>New>Apex Class for creating an Apex Class or File>New>Apex Trigger for creating an Apex Trigger
  • Creating from Setup:
Click on Gear icon, select Setup. From Setup Quick find box, type Apex, an select Apex Classes>New for creating an Apex class or select Apex Triggers>New for creating an Apex Trigger
  • Using third party code editors like Visual Code. Visual code needs to be configured before it can be used as a platform to code for Salesforce.

Follow steps from this link if you can to use Visual Studio code as a code editor for Salesforce:

Access Modifiers in Apex

Access Modifiers are used to define accessibility or scope of a class, method, or a variable. In Apex, defining the access modifier in top level Class is mandatory. For inner classes, defining the access modifier is optional and set to private by default. This means any inner class, method or variable without a access modifier is set to private.

Types of Access Modifiers in Apex:

  1. Private: Private methods or variables are the ones that can only be accessed within a class that they are defined in.
  2. Global: Global methods or variables can be accessed by any Apex code that has access to the class.
  3. Public: Defined as public means that a variable or method can be accessed by any Apex code defined in an application or a namespace.
  4. Protected: Defined as protected means that a variable or a method would be accessible by any inner class or classes that extend the outer class these variables or methods are defined in.

Datatypes in Apex:

Primitive Datatypes:

  1. Boolean: Datatype used as a flag for checking specified conditions. Can be assigned only 3 values — True, False, Null.
  2. String: Used to store set of characters written within single quotes.
  3. Integer: 32 bit number without a decimal point.
  4. Decimal: Used to store decimals fields, and is a automatically assigned to currency fields.
  5. Double: Double is similar to Decimal but is 64 bit number with a decimal point and is used to store large numbers.
  6. Long: 64-bit number without decimal point
  7. Date: Datatype used to store particular date. Date.newInstance (newInstance(year, month, day) is used for defining Time.
  8. DateTime: Used to store a particular date and time. DateTime.newInstance (year, month, day, hour, minute, second) is used for defining Time.
  9. Time: Used to store a particular time. Time.newInstance(hour, minutes, seconds, milliseconds) is used for defining Time.
  10. ID: Id is used to store 18 characters valid force.com identifier.
  11. Blob: Collection of binary data. Blog is used for storing attachments into a variable.

Note: System static methods are used for creating Date, DateTime and Time values. For eg: Time t = Time.newInstance (6,30,5,100);

  • sObject: In Salesforce, any sObject can be assigned to a generic sObject data type.
    For Eg: sObject con = new Contact();

Other ways to Define Objects:

# Defining a Standard Object: Account acc = new Account();

# Defining a custom Object: Custom__c obj = new Custom__c();

Non-Primitive Datatypes:

Collection Variables: Collection variables are datatypes used for storing collection of multiple primitive and non-primitive data types.

In Salesforce, collection variables can be of following types:

  • List: Ordered, indexed collection of primitive or non-primitive data types. List(s) are used when data is to be stored in specific order.
    Eg: List<Account> acc = [SELECT Name FROM Account];

Functions available for List Datatype:

  • Set: Unordered, unique collection of primitive or non-primitive data types. Set(s) are used when records need to be unique and no duplicate records must be allowed. Also, data doesn’t need to be stored in sequential order.
    Eg: Set<Integer> mySet = new Set<Integer>{1, 2, 3};

Functions available for Set Datatype:

  • Map: Map is a key-value pairs, where each key maps to a single value. Map(s) are used when records needs an identifier to be stored corresponding to them for easy access.
    Eg: Map<ID, Account> m = new Map<ID, Account>([SELECT Id, Name FROM Account LIMIT 10]);

Functions available for Map Datatype:

Few More ways to define variables:

  1. Enum: Enum is used to store set of constants. Eg: public enum week {SUN, MON, TUES, WED, THURS, SAT};
  2. Final: Final is used to set a value of a variable which cannot be altered afterwards, so basically Final is used to define constants. Eg: static final Integer gravity = 10;
  3. Static: Static variables are the ones that can be accessed directly and doesn’t need to initiallized. Eg: public static Integer num = 3;
  4. Transient: Transient is used to define variables that cannot be saved. Common usage of Transient is for a field on Vf page that is utilized only during a page request. Transient ensures that value of the variable is not transmitted as part of view state. Eg: transient public final String accountName { get; set; }

Rules of Conversion — Numeric Data Types:

Hierarchy in Numeric Data Types:

  • Decimal > Double > Long > Integer

Lower numeric types can be assigned to higher numeric types without any explicit conversion. But when assigning a higher numeric type to lower one Explicit conversion is required.

Writing Code in Apex:

Apex Classes: Apex classes are similar to classes in any other object oriented language. A class here also is a blueprint where inner classes, methods and variables can be defined and business logic could be defined.

Basic Syntax of an Apex Class:

For an outer class, Access Modifier is compulsory, and is set to public by default.

Apex Triggers: Apex triggers enables developers to run custom actions before or after an event takes place in Salesforce.

For Creating an Apex Trigger, an object needs to be selected for which it will be triggered:

Basic Syntax of an Apex Trigger:

Here, Trigger is a keyword used to define a Trigger and ‘TestTrigger’ is name of the Trigger that is defined on ‘Account’ object. ‘Before insert’ is a triggering event for this trigger, which means this trigger will only be executed if a before insert event is executed on Account object.

Triggering Events:

Broadly triggering events are divided into 2 parts:

1) Before Triggers: These triggers are used to update or validate records before they are saved in the database. These types of triggers are used when fields of a record needs to be set or modified before they are saved in the database or complex validations needs to be performed before a record is saved or deleted in/from a database.

Before Events:

  • Before Insert
  • Before Update
  • Before Delete

2) After Triggers: These triggers are used to update or validate records after they are saved in the database. They are used when a complex validation is required after a record is saved in database, and a record needs to be updated, deleted or inserted in some other object. They also enables developers access fields that are set by system, like record IDs.

After Events:

  • After Insert
  • After Update
  • After Delete
  • After Undelete

Declaring Variables and Methods in Apex:

--

--

Vaibhav Vaid
Vaibhav Vaid

Written by Vaibhav Vaid

I am a Salesforce Developer working at Deloitte Digital.

No responses yet