The Apex Master Class

What Is Variable Scope in Apex? (Master Class Ep. 11)

4 min read

Subscribe on YouTube

What Is Variable Scope?

This one’s a quick lesson, but do not skip it, because if you don’t understand scope you are going to spend a genuinely infuriating afternoon wondering why Apex claims it has never heard of a variable that is right there, five lines up, clearly declared, staring you in the face.

Variable scope just means: where in your code that variable actually exists.

That’s it. That’s the concept. The details are easier to see than explain, so let’s just look at some code.


Class Variables

A variable declared at the top of your class, outside any method, is a class variable (you’ll also hear “member variable” or “instance variable”). It’s available absolutely everywhere inside that class.

Apex
public class VariableScope
{
    private String classVariable = 'Cool String';

    private void methodScope()
    {
        //Totally fine. classVariable lives at the class level.
        classVariable = 'Taco Bell';
        System.debug(classVariable);
    }

    private void anotherMethod()
    {
        //Also totally fine. Still in scope. Still Taco Bell.
        System.debug(classVariable);
    }
}

Both methods can read it, both can change it. It’s the class’s variable, and every method in the class shares it.


Method Level Variables

Now declare one inside a method and the rules change completely:

Apex
public class VariableScope
{
    private void methodScope()
    {
        String methodVariable = 'I only exist in here';
        System.debug(methodVariable);   //fine
    }

    private void anotherMethod()
    {
        //COMPILE ERROR. Apex has genuinely never heard of this thing.
        System.debug(methodVariable);
    }
}

That second method won’t even save. As far as it’s concerned, methodVariable does not exist and never did.

When methodScope() finishes running, that variable is gone. Vanished. It only ever lived inside those curly braces.


Block Level Scope (The Sneaky One)

Here’s where people actually get burned. Scope doesn’t stop at methods. Any set of curly braces creates a new scope. If statements, for loops, try blocks, all of them.

Apex
private void blockScope()
{
    Boolean isCool = true;

    if (isCool)
    {
        String blockVariable = 'I live in the if statement';
    }

    //COMPILE ERROR. We left the braces, so it's gone.
    System.debug(blockVariable);
}

This one gets everybody at least once. You declare something inside an if, then try to use it after, and Apex acts like you’ve lost your mind.

The fix is to declare it outside the block and assign it inside:

Apex
private void blockScope()
{
    Boolean isCool = true;
    String blockVariable;          //declared out here, so it survives

    if (isCool)
    {
        blockVariable = 'I live in the if statement';
    }

    System.debug(blockVariable);   //works, prints the value (or null)
}

Note that if isCool had been false, blockVariable would still be null here. Which is fine, as long as you’re expecting it. Remember what I said in the variables episode about null being responsible for a heroic share of your future bugs? This is one of the places it sneaks in.


So Should Everything Just Be A Class Variable?

Ha. No. Please no.

I know it’s tempting. Stick everything at the top of the class, never think about scope again, problem solved forever. Except now every method in your class can quietly modify state that every other method depends on, and six months from now you’ll be trying to work out which of eleven methods is the one setting that value to null.

The rule of thumb is boring but correct: declare a variable in the narrowest scope that works. If only one method needs it, it belongs in that method. Class variables are for genuinely shared state.

Your future self will thank you. Or at least won’t curse you, which is roughly the same thing.


What’s Next

Scope in one line: a variable lives inside the curly braces it was declared in, and dies when you leave them. Class level braces mean the whole class. Method braces mean that method. If-statement braces mean that if statement.

The Apex Developer Guide has a short page on scope if you want the formal version.

I’ve been casually throwing the word “method” around for two episodes now without ever properly explaining it, which is frankly a bit rude of me. So in the next episode we fix that.

See you next time!


Get Coding With The Force Merch!!

We now have a redbubble store setup so you can buy cool Coding With The Force merchandise! Please check it out! Every purchase goes to supporting the blog and YouTube channel.

Get Shirts Here!
Get Cups, Artwork, Coffee Cups, Bags, Masks and more here!


Check Out More Coding With The Force Stuff!

If you liked this post make sure to follow us on all our social media outlets to stay as up to date as possible with everything!

Youtube
Patreon
Github
Facebook
Twitter
Instagram


Salesforce Development Books I Recommend

Advanced Apex Programming
Salesforce Lightning Platform Enterprise Architecture
Mastering Salesforce DevOps

Good Non-SF Specific Development Books:

Clean Code
Clean Architecture