DEVELOPER'S BLOG

CLEAR versus INIT11 jul2016

Category: AL Development Tags: al, funktion

CLEAR versus INIT in C/AL programming

Both AL functions have similar meaning and theoretically could be used to clear or initialize a record. There is however one important difference. One of the functions resets a Company in scope. So, we have to look at the other function: CHANGECOMPANY. Recently when refactoring an old and many times enhanced CodeUnit I encountered the following pattern. Let's assume that the current context is the 'Company A'.

Customer.CHANGECOMPANY('Company B');
 

...
CLEAR(Customer);
Customer.INIT;
Customer."No." := 'Anything'
...
Customer.INSERT;

Execution of the above code snipped will always insert a record to the 'Company A'. The reason behind is that CLEAR will affect setup made by CHANGECOMPANY. Therefore, the above code is inconsistent so one should remember the following rules when making adjustments.

CLEAR will affect CHANGECOMPANY and reset the scope to the company currently used.

Customer.CHANGECOMPANY('Company B');
...
CLEAR(Customer);
Customer.INIT;
Customer."No." := 'Anything'
...
Customer.INSERT;

INIT will clear all fields except primary key. It would be possible to use additionally CLEAR for particular Fields included in the Primary Key.

Customer.CHANGECOMPANY('Company B');
...
CLEAR(Customer."No.");
Customer.INIT;
Customer."No." := 'Anything'
...
Customer.INSERT;

However, in the above example the call to CLEAR seems to be unnecessary.

Recall CHANGECOMPANY after CLEAR function.

Customer.CHANGECOMPANY('Company B');
...
CLEAR(Customer);
Customer.CHANGECOMPANY('Company B');
Customer.INIT;
Customer."No." := 'Anything'
...
Customer.INSERT;

What I personally did to the code was a removal of the CLEAR function as in the first option.

Dynamics NAV TM (Navision) Developer and Consultant View Konrad Buczkowski's LinkedIn profile Konrad Buczkowski