Skip to content

Instantly share code, notes, and snippets.

@ernestasjuska
Last active October 11, 2022 10:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ernestasjuska/a44113b6cd8a004ba31d5adbfb99d4e2 to your computer and use it in GitHub Desktop.
Save ernestasjuska/a44113b6cd8a004ba31d5adbfb99d4e2 to your computer and use it in GitHub Desktop.
codeunit 99999 "My Global State"
{
SingleInstance = true;
var
LastOperationId: Guid;
AllowSmth: Boolean;
local procedure UpdateState(CurrentOperationId: Guid)
begin
if LastOperationId <> CurrentOperationId then
ClearState();
end;
local procedure ClearState()
begin
Clear(LastOperationId);
AllowSmth := false;
end;
[EventSubscriber(...)]
local procedure BeforePost()
begin
LastOperationId := GlobalOperationId;
AllowSmth := true;
end;
// Might not be called if an error occurs.
[EventSubscriber(...)]
local procedure AfterPost()
begin
ClearState();
end;
// Something that normally is not allowed.
[EventSubscriber(...)]
local procedure OnBeforeSmth(...)
begin
// Suppose an error occured during the posting and OnAfterPost was not called and AllowSmth was stil set to true at this point.
// We must set AllowSmth to false if this is some different operation.
// Check if we are already doing some different operation but globals are still not reset.
UpdateState(GlobalOperationId);
if not AllowSmth then
Error('This is only allowed during the posting');
end;
// Now there is still a problem with this code.
// If AL code does post -> smth -> post, then smth will be allowed when it shouldn't.
// It is caller/designer responsibility to ensure that GlobalOperationId will be randomized after the post operation.
// This could be done by only exposing Post method that handles any errors and creates new GlobalOperationId at the very end.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment