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)
PageNoNotCorrectMsg: Label 'Enter correct number of %1';
with bo do begin
if (PageCount <= 0) then
Price := PageCount * 2.5;
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:
CalculatePrice: Codeunit CalculatePrice;
Then all you need is to add the call to the PageCount field’s OnValidate trigger:
if PageCount = xRec.PageCount then exit;
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.