Function Overloading in Microsoft Dynamics NAV

Object oriented programming has the concept of function overloading, that is, an object can have multiple functions with the same name as long as their signatures (the combination of parameters and return value) are different. This allows an object to respond to a function call differently depending on the context.

But wait, what are you talking about? Microsoft Dynamics NAV doesn’t work like that. C/AL is not an object oriented language.

It’s true, but that doesn’t mean that some of the good reasons to use function overloading in other languages don’t apply to NAV development. Unscrambling the double negative in the previous sentence – the principle behind function overloading can still be helpful in NAV development.

Time for an example:

I’ve got an AddData function. We don’t need to worry too much about what it does for now other than it creates records in a table.

image

Later in the development I realise that I need a new field in the table that will be populated in some circumstances, but not most. The obvious solution is to add a new parameter to the existing function. But that will break my existing code, requiring a change to the function and any code that calls it.

Making changes to code that already works has an inherent risk that you’ll introduce bugs and so is something that should be minimised.

As already noted, I can’t have another function called AddData with a different signature, but I can do the next best thing.

image

Create a new function, AddDataWithControlType with the same parameters as AddData plus the new ControlType parameter I need. This has several benefits:

  • I avoid changing the AddData function and existing code that calls it – therefore I can’t introduce any bugs
  • My new function can reuse the AddData function that I know already works
  • I only call this new function when it is relevant. I don’t have to pass the ControlType parameter in scenarios where it won’t be used – it keeps the code cleaner and easier for someone else to read.

This is a fairly trivial example, but the concepts of minimising changes to existing code and reusing existing code are important and will help you to write more extensible and less buggy code.

An alternative approach to function overloading to consider is the Argument Table design pattern.

Leave a Reply