Variables and Data Types

Variables and Data Types in Salesforce Apex

In Salesforce Apex, variables are used to store and manipulate data throughout your code. Each variable is assigned a specific data type, which dictates the kind of data it can hold. Understanding how to declare and use variables with different data types is crucial for effective Apex programming.

1. Variables in Apex

A variable is essentially a named storage location in memory, which holds a value that can be used and modified in your Apex code. You must declare a variable before you use it, specifying its data type and an optional initial value.

Declaration Syntax:

DataType variableName = initialValue;

Example:

String userName = 'John Doe';

In this example, userName is a variable of the String data type, initialized with the value 'John Doe'.

2. Data Types in Apex

Apex provides several data types that you can use to define the kind of data a variable can hold. Below are some of the key data types you will encounter:

  1. Primitive Data Types
    • Integer: Stores whole numbers (e.g., Integer userAge = 30;).
    • Decimal: Stores numbers with decimal points (e.g., Decimal productPrice = 99.99;).
    • Boolean: Stores true or false values (e.g., Boolean isActive = true;).
    • String: Stores text data (e.g., String cityName = 'San Francisco';).
    • Date: Stores dates without time (e.g., Date birthDate = Date.newInstance(1990, 5, 21);).
    • DateTime: Stores dates and times (e.g., DateTime orderDate = DateTime.now();).
    • Time: Stores time without date (e.g., Time startTime = Time.newInstance(9, 0, 0, 0);).
  2. sObject Data Types
    • sObjects represent Salesforce records. Examples include standard objects like Account and Contact, as well as custom objects like Invoice__c.
  3. Collections
    • List: An ordered collection of elements (e.g., List<String> cities = new List<String>();).
    • Set: An unordered collection of unique elements (e.g., Set<Integer> uniqueNumbers = new Set<Integer>();).
    • Map: A collection of key-value pairs (e.g., Map<String, Integer> productInventory = new Map<String, Integer>();).
  4. Enum
    • A special data type that allows you to define a variable that can take one of a predefined set of values.

3. Detailed Example with Explanation

Let’s create a different scenario to illustrate the use of variables and data types in Apex.

Scenario: You are building a feature to manage customer orders. The system needs to calculate the total cost of an order based on the quantity of items purchased and apply a tax rate. The details of each order, including the customer’s name, are stored and can be retrieved when needed.

Apex Code Example:

public class OrderManager {

    // Primitive data type variables
    Integer quantity;      // Stores the quantity of items purchased
    Decimal itemPrice;     // Stores the price per item
    Decimal taxRate;       // Stores the tax rate as a percentage
    Decimal totalCost;     // Stores the total cost after applying tax

    // sObject data type variable
    Contact customer;      // Stores the customer record (Contact is a standard Salesforce sObject)

    // Enum example
    public enum OrderStatus { NEW, PROCESSING, COMPLETED } // Defines the status of an order

    // Constructor
    public OrderManager(Contact customer, Integer quantity, Decimal itemPrice, Decimal taxRate) {
        this.customer = customer;
        this.quantity = quantity;
        this.itemPrice = itemPrice;
        this.taxRate = taxRate;
    }

    // Method to calculate total cost including tax
    public void calculateTotalCost() {
        Decimal subTotal = quantity * itemPrice;
        Decimal taxAmount = (subTotal * taxRate) / 100;
        totalCost = subTotal + taxAmount;
    }

    // Method to return order summary
    public Map<String, Object> getOrderSummary() {
        Map<String, Object> summary = new Map<String, Object>();
        summary.put('Customer Name', customer.Name);
        summary.put('Quantity', quantity);
        summary.put('Item Price', itemPrice);
        summary.put('Total Cost', totalCost);
        return summary;
    }

    // Method to update order status
    public void updateOrderStatus(OrderStatus status) {
        // Example logic to update order status
        if (status == OrderStatus.COMPLETED) {
            System.debug('Order has been completed for customer: ' + customer.Name);
        } else {
            System.debug('Order status updated to: ' + status);
        }
    }
}

Explanation:

  1. Primitive Data Types:
    • Integer quantity: Holds the number of items purchased in the order.
    • Decimal itemPrice: Stores the price of each item as a decimal value.
    • Decimal taxRate: Stores the tax rate to be applied to the order, also as a decimal.
  2. sObject Data Type:
    • Contact customer: Represents the customer placing the order. Contact is a standard Salesforce object that stores customer information.
  3. Enum Data Type:
    • public enum OrderStatus { NEW, PROCESSING, COMPLETED }: Defines the different statuses an order can have, restricting the variable to these specific values.
  4. Collections:
    • Map<String, Object> getOrderSummary(): Returns a map containing the order details, including customer name, quantity, item price, and total cost. The use of a map allows for the flexible storage of key-value pairs where keys are strings and values can be of any type.

How It Works:

  • The OrderManager class is designed to manage customer orders by storing relevant information such as quantity, price, and tax rate.
  • The constructor initializes these values when an OrderManager instance is created.
  • The calculateTotalCost method calculates the total order cost, including tax.
  • The getOrderSummary method returns a map with details about the order, which can be easily accessed and displayed.
  • The updateOrderStatus method updates the status of the order using the OrderStatus enum.

Tutorials Deck

TutorialsDeck is striving to provide the best learning material on technical and non-technical subjects.

Languages

Web Technologies

Database

Trending Technologies

© 2024. All rights reserved.

Contact Us @ tutorialsdeck06@gmail.com