Global variables in a single instance codeunit

norsenynorseny Member Posts: 19
Hi experts ;)

I am wondering if there are any recommendations about using global variables in single instance codeunits in Business Central/NAV. Generally, in modern object oriented programming defining and using global variables should be avoided at all costs.

Are there any official guidelines for BC?

Here is an example where it is really tempting to use single instance codeunit global variables: I am using two subscribers - OnValidate Qty on Warehouse Receipt Line (1) and OnValidate Qty on Purchase Line (2).

(1) should update values on both Warehouse Receipt Line and on Purchase Line.

(2) should update only values on Purchase Line.

The problem is that when I call (1), it triggers my code in subscriber (2) - I don't want to do that. I don't have a handled boolean here in parameters, as those are standard OnValidate triggers.

What is the best approach? Is using single instance codeunit global variables a no-go here?


  • AlexeyShaminAlexeyShamin Member Posts: 67
    edited 2020-09-26
    In tis case i:
    1. create global variable (SkipTrigger) in Purchase Line
    2. Create function SetSkipTrigger to set value for global variable SkipTrigger
    3. Create function GetSkipTrigger to get value for global variable SkipTrigger
    4. In (1) before update value in Qty field I set skipTrigger on TRUE. (Rec.SetSkipTrigger);
    5. In (2) if Rec.GetSkipTrigger = TRUE then EXIT;

    and I don't like to use single Codeunit in this case.
  • norsenynorseny Member Posts: 19
    AlexeyShamin, thank you for the suggestion, it's pretty cool! Works not only in NAV, but also in BC when defined on a tableextension object for Purchase Line. The important thing is to remember to pass PurchLine as a var parameter, e.g.:DoSomething(var PurchLine: Record "Purchase Line"...).

    Still wondering if there are any recommendations about single instance codeunit, anyone else?
Sign In or Register to comment.