New Rule: Detect global variables that could be local variables #499
Replies: 2 comments 5 replies
|
The rule is useful in principle but “used by only one procedure” does not prove that a global variable can safely become local. A simple counterexample is a variable that retains state between calls: var
Counter: Integer;
procedure GetNextNumber(): Integer
begin
Counter += 1;
exit(Counter);
end;Moving Another well-known example is the procedure GetRecordOnce()
begin
if RecordHasBeenRead then
exit;
Get();
RecordHasBeenRead := true;
end;Although Therefore "used by only one procedure" should only identify a candidate. Stateful variables need additional analysis, while stateless variables such as |
|
I’ve reviewed last year a PR from @iwanscheidsnc for this: Unfortunately at that moment in time we’ve decided to not go through with it. A fresh view on this is a great idea, where you can read some considerations on the comments of the PR. |

Uh oh!
There was an error while loading. Please reload this page.
Title
Detect global variables that could be local variables
Description
A global variable should not be declared at object scope when it is only used by a single procedure.
The analyzer should detect global variables where all references are contained within one procedure and suggest moving the variable declaration to that procedure's local
varsection.Example:
Customeris only used byDoSomething()and could therefore be declared as a local variable:Keeping variables at the smallest possible scope makes dependencies clearer and avoids unnecessary object state. This is especially relevant for record variables, where filters, keys, field values, marks, etc. may otherwise persist as part of the object state.
I have especially detected this in code converted from classic C/AL to AL.
All reactions