How To Determine Whether Tn Organization Is A Sandbox Or Production in Apex

Salesforce features an object known as Organization, equipped with a standard field called IsSandbox. This field proves useful for identifying whether Apex code is executing in a production or sandbox environment. If the organization is a sandbox, the IsSandbox field will return true.

A lazy loader can be developed for utilization by other classes, with the ideal placement being in a utility class for seamless integration into various classes. However, in this particular example, it is situated in a standalone class.

public class SandboxExample {

    /**
     * Lazy loader method
     */
    public static Boolean runningInASandbox {
        get {
            //check if boolean has been set yet
            if (runningInASandbox == null) {
                runningInASandbox = [SELECT IsSandbox FROM Organization LIMIT 1].IsSandbox;
            }
            //Return value
            return runningInASandbox;
        }
        set;
    }
}

The previously provided code can now be referenced in other classes whenever there is a need to determine whether the organization is a sandbox or production environment, using the following code.

public static void sampleMethod(){
        System.debug('Is running in sandbox: '  + SandboxExample.runningInASandbox);
}

In an ideal scenario, resorting to a SOQL query wouldn’t be necessary to obtain this information. However, using the domain.getSandboxName() approach poses challenges when dealing with scratch orgs.