Salesforce Apex Development - Apex Fundamentals

 


Hi Everyone,
I have started the blog series for Salesforce Apex development, so if you want to learn more then follow my blog post.

APEX FUNDAMENTALS

As you already know, Apex is a programming language that uses Java-like syntax and acts like database stored procedures. Apex enables developers to add business logic to system events, such as button clicks, updates of related records, and controllers for Aura Component, Lightning Web Component, and Visualforce pages.

Data Types in Apex

Apex supports various data types, including a data type specific to Salesforce—the sObject data type, which is the Salesforce object like Account, Contact, custom object, etc.

Apex supports the following data types:-

  • A primitive, such as an Integer, Double, Long, Date, Datetime, String, ID, Boolean, among others.
  • An sObject, either as a generic sObject or as a specific sObject, such as an Account, Contact, or MyCustomObject__c (you’ll learn more about sObjects in a later unit.)
  • A collection, including:
    • A list (or array) of primitives, sObjects, user defined objects, objects created from Apex classes, or collections
    • A set of primitives
    • A map from a primitive to a primitive, sObject, or collection
  • A typed list of values, also known as an enum
  • User-defined Apex classes
  • System-supplied Apex classes
Let's discuss each data type in more detail.

Primitive Data Types

Apex uses the same primitive data types as SOAP API, except for higher-precision Decimal type in certain cases. All primitive data types are passed by value.

All Apex variables, whether they’re class member variables or method variables, are initialized to null. Make sure that you initialize your variables to appropriate values before using them. For example, initialize a Boolean variable to false.

Apex primitive data types include:

Integer

  • A 32-bit number that does not include a decimal point. Integers have a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647. For example:- 
  
  Integer i = 1;
  
  

Long

  • A 64-bit number that does not include a decimal point. Longs have a minimum value of -263 and a maximum value of 263-1. Use this data type when you need a range of values wider than the range provided by Integer. For example:
  
Long l = 2147483648L;
  
  

Decimal

  • A number that includes a decimal point. Decimal is an arbitrary precision number. Currency fields are automatically assigned the type Decimal.
Example:-
    
      Decimal dec = 10.01;
      
      
Double

  • A 64-bit number that includes a decimal point. Doubles have a minimum value of -263 and a maximum value of 263-1. For example:
  • 
      Double dec = 10.01;
      Double pi = 3.14159;
      Double e = 2.7182818284D;
      
      

String

  • Any set of characters surrounded by single quotes. For example,
  • 
        String s = 'Follow the avnishyadav.com.';
        
  • String size: Strings have no limit on the number of characters they can include. Instead, the heap size limit is used to ensure that your Apex programs don't grow too large.

Boolean

  • A value that can only be assigned as true, false, or null. For example:
  • 
        Boolean isValid = true;
        


Date

  • A value that indicates a particular day. Unlike Datetime values, Date values contain no information about time. Always create date values with a system static method.
  • You can add or subtract an Integer value from a Date value, returning a Date value. Addition and subtraction of Integer values are the only arithmetic functions that work with Date values. Instead, use the Date methods.
DateTime

  • A value that indicates a particular day and time, such as a timestamp. Always create DateTime values with a system static method.
  • You can add or subtract an Integer or Double value from a Datetime value, returning a Date value. Addition and subtraction of Integer and Double values are the only arithmetic functions that work with Datetime values. Instead, use the Datetime methods.


Time

  • A value that indicates a particular time. Always create time values with a system static method. See Time Class.


ID

  • Any valid 18-character Lightning Platform record identifier. For example:
  • 
        ID idcon='00300000003T2PGA0';
        
  • If you set ID to a 15-character value, Apex converts the value to its 18-character representation. 
  • All invalid ID values are rejected with a runtime exception.


Blob

  • A collection of binary data stored as a single object. 
  • You can convert this data type to String or from String using the toString and valueOf methods, respectively. 
  • Blobs can be accepted as Web service arguments, stored in a document (the body of a document is a Blob), or sent as attachments. 
  • For more information, see Crypto Class.


Object

  • Any data type that is supported in Apex. Apex supports primitive data types (such as Integer), user-defined custom classes, the sObject generic type, or an sObject-specific type (such as Account). All Apex data types inherit from Object.
  • You can cast an object that represents a more specific data type to its underlying data type. For example:
  • 
       Object obj = 10;
      // Cast the object to an integer.
      Integer i = (Integer)obj;
      System.assertEquals(10, i);
        
  • The next example shows how to cast an object to a user-defined type—a custom Apex class named MyApexClass that is predefined in your organization.
  • 
       
          Object obj = new MyApexClass();
          // Cast the object to the MyApexClass custom type.
          MyApexClass mc = (MyApexClass)obj;
          // Access a method on the user-defined class.
          mc.someClassMethod();
        


Collection Data Types

Collections in Apex can be lists, sets, or maps.

Lists

  • A list is an ordered collection of elements that are distinguished by their indices. 
  • List elements can be of any data type—
    • primitive types, 
    • collections, 
    • sObjects, 
    • user-defined types, and 
    • built-in Apex types.
    
              // Create an empty list of String
              List<String> my_list = new List<String>();
              // Create a nested list
              List<List<Set<Integer>>> my_list_2 = new List<List<Set<Integer>>>();
    
         
Note: - All lists are initialized to null. Lists can be assigned values and allocated memory using literal notation. For example:

          //Defines an Integer list of size zero with no elements
          List<Integer> ints = new Integer[0];

          //Defines an Integer list with memory allocated for six Integers
          List<Integer> ints = new Integer[6];

     

Sets

  • A set is an unordered collection of elements that do not contain any duplicates. 
  • Set elements can be of any data type—
    • primitive types, 
    • collections, 
    • sObjects, 
    • user-defined types, and 
    • built-in Apex types.
  • To declare a set, use the Set keyword followed by the primitive data type name within <> characters. For example:
  • 
              Set<String> myStringSet = new Set<String>();
    
            // Defines a new set with two elements
            Set<String> set1 = new Set<String>{'New York', 'Paris'};
         

  • Apex uses a hash structure for all sets.
  • A set is an unordered collection—you can’t access a set element at a specific index. You can only iterate over set elements.

Maps

  • A map is a collection of key-value pairs where each unique key maps to a single value. Keys and values can be any data type—primitive types, collections, sObjects, user-defined types, and built-in Apex types.
  • Map keys and values can contain any collection, and can contain nested collections. For example, you can have a map of Integers to maps, which, in turn, map Strings to lists. Map keys can contain up to seven levels of nested collections, that is, up to eight levels overall.
  • To declare a map, use the Map keyword followed by the data types of the key and the value within <> characters. For example:
  • 
              Map<String, String> country_currencies = new Map<String, String>();
              Map<ID, Set<String>> m = new Map<ID, Set<String>>();
    
              //map key-value pairs when the map is declared by using curly brace ({}) syntax. 
              //Within the curly braces, specify the key first, then specify the value for that key using =>
              Map<String, String> MyStrings = new Map<String, String>{'a' => 'b', 'c' => 'd'.toUpperCase()};
    
              //To get value from map
              MyStrings.get('a');
         
  • Apex uses a hash structure for all maps.

Parameterized Typing

Apex, in general, is a statically-typed programming language, which means users must specify the data type for a variable before that variable can be used. For Example

    	//This is legal in Apex:
		Integer x = 1;
     
But

      	//This is not legal, if y has not been defined earlier:
		y = 1;
     

Enum Data Types

  • An enum is an abstract data type with values that each take on exactly one of a finite set of identifiers that you specify. 
  • Enums are typically used to define a set of possible values that don’t otherwise have a numerical order. Typical examples include the suit of a card or a particular season of the year.
  • To define an enum, use the enum keyword in your declaration and use curly braces to demarcate the list of possible values. For example, the following code creates an enum called Season:
  • 
          	public enum Season {WINTER, SPRING, SUMMER, FALL}
         
  • For more information, see Enum Methods.

Variables

  • Local variables are declared with Java-style syntax. As with Java, multiple variables can be declared and initialized in a single statement.
  • Local variables are declared with Java-style syntax. For example:
  •       	
            Integer i = 0;
            String str;
            List<String> strList;
            Set<String> s;
            Map<ID, String> m;
            Integer i, j, k;
    
            
            
          
  • To avoid confusion with case-insensitive SOQL and SOSL queries, Apex is also case-insensitive.

Constants

  • Apex constants are variables whose values don’t change after being initialized once. Constants can be defined using the final keyword.
  •       	
             static final Integer PRIVATE_INT_CONST = 200;
     
          
  • The final keyword means that the variable can be assigned at most once, either in the declaration itself or with a static initializer method if the constant is defined in a class
Most of the parts of the tutorials are referenced from Standard Apex Guide.

Connect/Follow for more information on Salesforce Apex.

Thanks!









Next Post Previous Post
No Comment
Add Comment
comment url