Understanding Static Methods and Variables in Apex

Understanding Static Methods and Variables in Apex

We use static daily in our coding life, but do we actually know its usage? When working with Apex, it's crucial to understand the role of static methods and variables, especially in the context of outer and inner classes. Here’s a straightforward guide with examples.

Static Methods and Variables: The Basics

Static Methods and Variables: You can only use static methods and variables with outer classes. Inner classes cannot have static methods or variables.

No Instance Required: A static method or variable doesn’t need an instance of the class to be accessed or run.

How Do They Work?

Before you make any objects from a class, all the static variables in that class get set up, and any code blocks specifically for static stuff run. It all happens in the order they're written in the class.

public class ExampleClass {
    // Static variable
    public static Integer count = 0;

    // Static initialization block
    static {
        count = 5;
    }
}

// When ExampleClass is loaded, count becomes 5
ExampleClass exClass = new ExampleClass();
System.debug(ExampleClass.count);        

Static Methods in Action

Static methods are like handy tools that don’t need any object to work. They can't access variables tied to a specific object. Which means ??

For the class - ExampleClass.

This will work:
ExampleClass exClass = new ExampleClass();
System.debug(ExampleClass.count);

This won't.
ExampleClass exClass = new ExampleClass();
System.debug(exClass.count); //since it is an instance of the object created in the above line        

In Apex, static variables are only 'static' within one transaction. They keep their value throughout one transaction but reset in the next.

public class Counter {
    public static Integer count = 0;

    public static void increment() {
        count++;
    }
}

// During a single transaction
Counter.increment();
Counter.increment();
System.debug(Counter.count); // Output: 2

// In a new transaction, Counter.count resets to 0        

To store information that is shared across instances of a class, use a static variable. All instances of the same class share a single copy of the static variable. For example, all triggers that a single transaction spawns can communicate with each other by viewing and updating static variables in a related class. A recursive trigger can use the value of a class variable to determine when to exit the recursion.

Example 1:

public class TriggerHelper {
    // Static variable to keep track of something in triggers
    public static Integer triggerCount = 0;
}

trigger AccountTrigger on Account (before insert, before update) {
    // Increment the trigger count
    TriggerHelper.triggerCount++;
    System.debug('Trigger Count: ' + TriggerHelper.triggerCount);
}

// If the trigger fires multiple times in one transaction, TriggerHelper.triggerCount will remember the count        

Example 2:

You can make use of the first run variable across classes to stop the recursive run of a trigger

public class ExampleClass { 
   public static boolean firstRun = true; 
}        
trigger ExampleTrigger on Contact (before delete, after delete, after undelete) { 
       if(Trigger.isBefore){
          if(Trigger.isDelete){
             if(p.firstRun){
                 Trigger.old[0].addError('Before Account Delete Error');
                  p.firstRun=false;
              } 
           }
        }
}        

Additional Points to Note

  • Static Variables in Triggers: A static variable defined in a trigger doesn't retain its value between different trigger contexts within the same transaction. Instead, define static variables in a class so that the trigger can access these class member variables and check their static values.


Let's break down this explanation with an example: Suppose we have a scenario where we want to count the number of times a trigger is fired during a single transaction. We might be tempted to use a static variable directly within the trigger to keep track of this count. However, due to the nature of how triggers are executed in Salesforce, this approach wouldn't work as expected.

trigger AccountTrigger on Account (before insert, after insert) {
    // Static variable to count trigger invocations
    public static Integer triggerCount = 0;

    if (Trigger.isBefore) {
        triggerCount++;
    } else if (Trigger.isAfter) {
        System.debug('Trigger Count: ' + triggerCount); // Output: Always 0
    }
}        

In the above trigger, we define a static variable triggerCount to count the number of times the trigger is invoked. However, when the trigger fires the after insert context, the triggerCount always prints as 0, even though it was incremented in the before insert context.

Why does this happen?

In Salesforce, each trigger context (e.g., before insert, after insert) is executed separately within the same transaction. When the after insert context runs, it's essentially a new execution context that starts from scratch, meaning the static variable from the before insert context is not retained.

To solve this issue, we define the static variable in a separate class rather than directly within the trigger.

  • Accessing Static Variables: A class static variable can’t be accessed through an instance of that class. Use the class name to refer to static identifiers.
  • Local Variable Names: Local variable names are evaluated before class names. Be cautious of naming conflicts between local variables and class names.
  • Inner Classes: An inner class behaves like a static Java inner class, but doesn’t require the static keyword. It can have instance member variables like an outer class, but there’s no implicit pointer to an instance of the outer class.


Understanding these concepts can help you write better Apex code and make the most out of static methods and variables in Salesforce!



Reference: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_static.htm

Kowsalya Venkadachalam

4x Certified | Platform Developer 2 | Platform Developer 1 | Salesforce Administrator | Salesforce AI Associate | Senior Salesforce Developer at Inno Valley Works

9 个月

Interesting!

要查看或添加评论,请登录

Yadhu Krishnan的更多文章

社区洞察

其他会员也浏览了