5

I predicted we would run into recursive triggers with a project that we are currently working on. To pre-empt this, I searched for solutions and came across this:

Avoiding Recursive Triggers

I modified the code to the following:

public class checkRecursive {
    public static integer runCount {
        get {
            return runCount == null ? 0 : runCount++;
        }
    }
}

The code provided by Salesforce does infact prevent the recursive triggers. My code does not. I'm curious to know the reasoning behind it. Primarilly, since my code is short hand for the following:

public class checkRecursive {
    public static integer runCount;

    public static integer getRunCount() {
        if (runCount == null) {
            return 0;
        } else {
            return runCount++;
        }
    }
}

Which to me, doesn't look a whole lot different from what is provided by salesforce.

1 Answer 1

8

The difference is that you never set runCount, so it remains null each time it's called. Try this:

public class checkRecursive {
    public static integer runCount;

    public static integer getRunCount() {
        if (runCount == null) {
            return runCount = 0; // Assigns 0 to runCount, and returns 0.
        } else {
            return ++runCount; // Increment value, then return.
        }
    }
}

Also, the original version you quoted would have the same problem; it should really be:

public class checkRecursive {
    public static integer runCount {
        get {
            return runCount == null ? runCount = 0 : runcount++;
        }

        set;
    }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .