Well the idea of having a codeunit do “the job” is brilliant. Right after “the book” of clean structured AL coding. Moving everything to the table object (as suggested) is how you would do it in Navision C/AL, where we often had the bad habit of considering objects, when doing our development. Resulting in source code which is hard to “read”, difficult to maintain and challenging to extend. In Navision you often see tables and pages with tons of code and large “My Solution Management” codeunits which are a mixture of all kinds of functions.
In Business Central you need not to worry about object costs (except on-premise) and its a must that you code is extendable, just as you need the standard code to be extendable.
If you were to solve you example (I expected that is is a thought example - nobody would calculate the price of a book by using the number of pages…) in Business Central VSCode/AL, then I would think the codeunit as method. In your case method CalculatePrice. In it’s simples fashion, then it only contains of public function:
procedure CalculatePrice(var Book: Record Book)
var
PageNoNotCorrectMsg: Label 'Enter correct number of %1';
begin
with bo do begin
if (PageCount <= 0) then
Message(PageNoNotCorrectMsg,FieldCaption(PageCount))
else
Price := PageCount * 2.5;
end;
end;
This way, whenever you need to change something regarding how your price is calculated, then all you need to do is to change this codeunit. You don’t need to “jeopardize” other parts of your code. You would also need to implement the method by creating it in the book table object:
procedure CalculatePrice();
var
CalculatePrice: Codeunit CalculatePrice;
begin
CalculatePrice.CalculatePrice();
end;
Then all you need is to add the call to the PageCount field’s OnValidate trigger:
trigger OnValidate();
begin
if PageCount = xRec.PageCount then exit;
CalculatePrice();
end;
I know it requires more code and more objects, but it’s really the way to go if you want to develop for Dynamics 365 Business Central. You don’t want to repeat mistakes we have done in Navision. I can really recommend you to want this video by by MVP friend Gary Winter.
[embed:b99cc4af-f990-4d68-b98f-dd11f41cb350:717196e1-4b3f-4b7f-ac88-553648d8dc19:service=youtube&embedCode=%3Ciframe%20width%3D%22560%22%20height%3D%22315%22%20src%3D%22https%3A%2F%2Fwww.youtube.com%2Fembed%2FJCMx2BwKtrc%22%20frameborder%3D%220%22%20allow%3D%22autoplay%3B%20encrypted-media%22%20allowfullscreen%3E%3C%2Fiframe%3E&scriptProperty=]