Apex Programming Fundamentals
Introduction
- Apex is used to manipulate business objects programmatically within enterprise systems.
- Covers Apex programming syntax, data types, and data structures.
What is Apex?
- A strongly typed, object-oriented programming language.
- Executes flow and transaction control statements on Salesforce servers with API calls.
- Uses syntax similar to Java and C#.
- Adds business logic to system events like button clicks and record updates.
- Initiated by web service requests and object triggers.
Key Features
- Integrated with Salesforce: Custom logic and automation within Salesforce.
- Strongly Typed: Variables require specific data type declarations.
- Object-Oriented: Supports classes, objects, inheritance, and polymorphism.
- Multitenant Environment: Safe and efficient execution for multiple users.
- Database Integration: Easy data querying and manipulation using SOQL and DML.
How Apex Works
- Runs on-demand on the Salesforce Lightning Platform.
- Code is compiled into abstract instructions and saved as metadata.
- Runtime interpreter executes compiled instructions when triggered by user actions.
Typical Apex Program
- Includes SOQL queries, variable declarations, control structures, and DML operations.
- Every Apex statement ends with a semi-colon.
Integer NUM = 10
- Example operations:
- Variable Declaration
- Control Structure
- Array (List)
- Data (DML) Operation
Salesforce Application Anatomy
- View: User Interface (Standard and Custom Objects, Page Layouts, Lightning Pages).
- Controller: Business Logic (Workflow Rules, Process Builder, Lightning Flows for declarative tools; sObjects, Apex Classes, Triggers, Visualforce, Lightning Components for programmatic tools).
- Model: Database (supports Apex Programming).
Apex Development Environment
- Force.com development environment.
- Development Tools:
- Force.com Developer Console.
- Code editor in Salesforce user interface.
- Visual Studio Code.
Apex Syntax: Data Types
- Strongly typed language; variables must be declared before use.
- Data Types:
- Primitive (Integer, Double, Long, Date, Datetime, String, ID, Boolean)
- Collections (Lists, Sets, Maps)
- sObject
- Enums
- Classes, Objects, Interfaces
Primitive Data Types
- Integer: 32-bit number without decimal points (e.g.,
latex Integer occupancyLimit = 5;). - Boolean: true, false, or null (e.g.,
latex Boolean availabilityStatus = true;). - Date: Stores date only (e.g.,
latex Date reservationDate = new Date.today();). - Long: 64-bit number without decimal points (e.g.,
latex Long hotelRevenue = 45233299393939393L;). - String: Set of characters within single quotes (e.g.,
latex String hotelName = ‘GrandStand Hotels’;).
Primitive Data Type: sObject
- Represents Salesforce objects (Standard or Custom).
- Example:
//Declaring an sObject variable of type Hotel
Hotel myHotel = new Hotel();
//Assignment of values to fields of sObjects
myHotel.hotelID = 'HT0004';
myHotel.Name = 'Royal Hotels';
myHotel.Address = '123 Downtown Street';
myHotel.Location = 'Brisbane CBD';
// Display myHotel variable values
System.debug('My Hotel Variable Values: '+myHotel);
- Multiline comments:
latex /* ... */ - Single-line comments:
latex // ...
Apex Syntax: Variables
- Must be declared before use (strongly typed language).
- Example:
latex String roomName = ‘Corner Room’;latex Integer occupancyLimit = 4;latex Boolean availability = true;
Apex Syntax: Constants
- Declared using the
final keyword; values cannot be changed after initialization. - Example:
latex final Decimal PricePerNight = 150.00;latex final String RoomName= ‘Lincoln Room';
Apex Syntax: Enum
- Defines a set of named values.
- Example:
public enum RoomTypes { DELUXE, STANDARD, DOUBLE }
RoomType roomType = RoomTypes.DELUXE;
System.debug('The room type is: ' + roomType);
Apex Syntax: Arithmetic Operations
- Addition, subtraction, multiplication, division.
- Example:
Integer number1 = 10;
Integer number2 = 5;
Integer sum = number1 + number1; // Addition
Integer difference = number1 - number1; // Subtraction
Integer product = number1 * number1; // Multiplication
Integer quotient = number1 / number1; // Division
Apex Syntax: Logical Operators
latex == (equals), latex != (not equal), latex < (less than), latex <= (less than or equal to), latex > (greater than), latex >= (greater than or equal to), latex && (and), latex || (or), latex ! (not).
Apex Syntax: String Operations
- Concatenation, length, substring.
- Example:
latex String fullName = firstName + ' ' + lastName;latex Integer nameLength = fullName.length();latex String firstInitial = firstName.substring(0, 1);
Decision Making
- if statement: Executes code if a condition is true.
if (isLoyaltyMember) {
pricePerNight = pricePerNight * 0.9; // 10% discount
}
- if…else statement: Executes code if a condition is true, otherwise executes the else block.
if (roomAvailabile) {
System.debug('Room is available. ’);
} else {
System.debug('Room is not available for booking. ’);
}
- if…elseif…else statement: Tests multiple conditions.
if (roomCode == 'STD’) {
roomType = 'Standard';
} else if (roomCode == 'DLX’) {
roomType = 'Deluxe';
} else {
roomType = 'Unknown';
}
- nested if statement: An if statement inside another if statement.
if (roomAvailable) {
if (isLoyaltyMember) {
pricePerNight = pricePerNight * 0.85; // 15% discount
}
}
- switch statement: Evaluates a variable against multiple values.
switch on requestCode {
when 'TOW' {
department = 'Housekeeping';
}
when else {
department = 'Unknown';
}
}
Loops in Apex
- for loop: Executes a code block a specific number of times.
for (Integer i = 1; i <= numberOfNights; i++) {
totalCost += nightlyRate;
}
- while loop: Executes a code block as long as a condition is true. Condition is checked first before each iteration.
while (! roomAvailability && roomNumber <= 210) {
roomAvailability = (Math.random() < 0.2);
if(! roomAvailability){
roomNumber++;
}
}
- do-while loop: Executes a code block once before checking the condition. Which mean it will execute at least once.
do {
roomNumber = Integer.valueOf(Math.round(Math.random() * 300));
if (roomNumber >= 101 && roomNumber <= 300) {
validRoom = true;
} else {
System.debug('Invalid room number. Please enter a number between 101 and 300. ');
}
} while (!validRoom);
Break and Continue Statements
- break: Exits the loop.
- continue: Skips the current iteration and proceeds to the next.