Static vs Instance Methods

A static method has the static key word in the signature. By being declared static, it means it is associated with the class and not any specific instance of the class. In Apex, a static method can only be called from the class, while an instance method can only be called from an object.

An important note for developers that are accustomed to other OO languages:
static in Apex means there is only one version of the method or field per execution context. Unlike most other languages, if two users are simultaneously hitting the same static method, each user gets a different version. Also note there is no mechanism in Apex to lock a static field to prevent concurrency issues; however, it is not needed in Salesforce.

Often one questions whether a field or method should be declared as static or whether it should be an instance field or method. As usual, there is not a single correct answer.

The performance of calling the method is virtually the same; however, since one must instantiate an object of the class to call an instance method, there is a small hit to overall performance, cpu time, and heap size.

Additional considerations:
  • Static methods cannot be made virtual and cannot be overridden.
  • Static methods cannot be mocked for unit testing.
  • Static methods cannot access instance fields.
  • Static methods are often easier to call.
    E.g.

    MyClass.method();

    ...compared to:

    MyClass mc = new MyClass();
    mc.method();

  • Static methods can more easily be moved to other classes since they don't rely on instance fields of the given class.

In most cases, I prefer to use static methods for utility methods, and reserve them only for less complex functionality I do not care to mock for testing.

For static fields, the answer is simpler: if there only needs to be one value for all instances, use a static field, otherwise use a method field.

 

 

© 2001 – 2023 Object Factory Inc
marker marker marker marker marker