Function libraries and interfaces

Not every function in Microsoft Dynamics NAV has a clear owner. In some cases, we have a function that can be accessed using simple variables that perform some calculation or a small piece of business logic.

These functions can be put in function libraries or interfaces. By doing this, it is easy for other developers to reuse them.

Examples of function libraries can be string manipulations or date functions. Microsoft Dynamics NAV does not have a lot of built-in functions for this, and many developers have created their own collection of functions through the years.

An Interface is a reusable component that can be accessed from anywhere in the application. A very good example of what could and should be an interface is the function called DateNotAllowed in Codeunit 11, Gen. Jnl.-Check Line:

IF (AllowPostingFrom = 0D) AND (AllowPostingTo = 0D) THEN BEGIN
  IF USERID <> '' THEN
    IF UserSetup.GET(USERID) THEN BEGIN
      AllowPostingFrom := UserSetup."Allow Posting From";
      AllowPostingTo := UserSetup."Allow Posting To";
    END;
  IF (AllowPostingFrom = 0D) AND (AllowPostingTo = 0D) THEN BEGIN
    GLSetup.GET;
    AllowPostingFrom := GLSetup."Allow Posting From";
    AllowPostingTo := GLSetup."Allow Posting To";
  END;
  IF AllowPostingTo = 0D THEN
    AllowPostingTo := 31129999D;
END;

This function uses the Multi-Level setup Pattern to check the User Setup and General Ledger Setup for allowed posting dates. This function is reused in Codeunit 80 and Sales-Post, and is cloned in other functions such as Codeunit 211, Res. Jnl.-Check Line and Codeunit 21, and Item Jnl.-Check Line.

Instead of calling a function from another Codeunit or cloning functions, we could create a new Codeunit Posting Date Allowed Iface. This Codeunit only has one global function that does what we expect; or it may even have multiple global functions if we have a requirement for having small variances.

The naming of Codeunits is very important to increase the chance of the functions to be reused. When not reused the result will be code cloning, an anti-pattern, which we will discuss in Chapter 6, Anti-patterns and Handling Legacy Code.

Some development environments such as eclipse have plugins that search for code clones. Microsoft Dynamics NAV does not have a plugin as this.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset