Wednesday 8 September 2010

Static boolean variables as "Locks"

Over 6 months and no new posts, tsk tsk! I'm trying to get back into the habit (though did I ever really have it?) with some - hopefully! - short, sharp posts.

So - do you use static boolean variables to control trigger flow and behaviour? I do - a lot. A common use is when Object A has a trigger that does something to Object B, and Object B has a trigger that does something to Object A. To avoid recursion when you update one, you can use a static boolean to cause the second trigger to return immediately rather than execute it, which causes the first trigger to fire again yadda yadda yadda. Similarly, if you have workflow that will cause an update to a record and you don't want triggers firing a second time, a static boolean does the job.

The advice in this post is simple: I think it's a good idea to keep these variables in a separate class. This is due to recent experiences, when I needed such a static variable in a class. I took the easy route and put it in the same class, and this was OK initially. Later, I needed to access that variable from somewhere else, which was possible, however, in that same class I also had a static code block in the same class that queried the database and set some variables.

Now, just by looking at this variable from outside the class, I was causing queries against the database to happen. I had enough headroom for this at the time but in the long term, it's a potential headache waiting to happen.

The solution is to have a separate class that holds such variables and refer to them from other points of code that need to look at them, rather than have the booleans amongst classes scattered here, there and every where. It'll be easier to manage and is better in the long run.

No comments:

Post a Comment