What you have here is not a singleton pattern. The singleton pattern is one that restricts the instantiation of a class to just a single instance (see, for example, Geeks for geeks, Refactoring Guru, and Wikipedia). You haven't restricted Boolean from being used anywhere else in the system (nor could you), so this isn't a singleton pattern. Most developers would simply call this a publicly read-only static variable.
With that out of the way, the other answers point out that unit tests will be crippled with this design, and I agree. Unlike the other answers, I would suggest that the better solution would be to have a private test-visible backing variable. This allows your code to still be safe from accidental overwrites by a developer just trying to get something to work in production code, rather than only for unit tests.
As such, my approach to this would look something more like this:
@TestVisible private static Boolean private_IsSandboxFlag;
public static Boolean isSandbox {
public get {
if(private_IsSandboxFlag == null) {
private_IsSandboxFlag = [SELECT IsSandbox FROM Organization].IsSandbox;
}
return private_IsSandboxFlag;
}
private set;
}
This prohibits live code from altering the flag at compile-time, but allows unit tests to set a value in order to test alternative branches of code that depend on this flag. As an experienced developer, I've seen this happen far too many times by accident. That's because the assignment operator =
returns the r-value after assigning the r-value to the l-value. In other words, without the private set
, it's possible to accidentally write:
if(Utils.isSandbox = true) {
Or:
while(Utils.isSandbox = true && hasMoreData()) {
Etc.
The private set
is there for safety. We don't want to write to the variable at all in production code, so we lock it down to prevent accidents that can be hard to track down when you've got a lot of code to look through.