ENTWICKLER-BLOG

CLEAR versus INIT11 Jul2016

Kategorie: NAV Development Tags: c/al, function

CLEAR versus INIT in C/AL programming

This question has been asked many times and there is no clear solution. Each approach is good when properly used. However there is one obvious but important difference between these functions that one might not forget.

A magic keyword is the other function CHANGECOMPANY. Recently when refactoring an old and many times enhanced CodeUnit I encontered the foloowing 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 incosistent so one should remember the following rules when making adjustments.

CLEAR will affect CHNAGECOMPANY 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 fileds except primary key. It would be possible to use additinally CLEAR for particular Fields inluded 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.

View Konrad Buczkowski's LinkedIn profile Konrad Buczkowski