The everyday life of a Dynamics AX developer
In this post I want to show you the use of the new() and construct() method when instantiating classes using a simple example class. This is a design that is used a lot an AX.
Like a good recipe, a good class has a few important ingredients:
- Parm methods for variables
- A protected new method
- A static contructor
- A run method
As an example, we will create a new class: KLFShowRecordInfo
The function of the class will be to display some information about a record.
This class has one variable, a record. The type is Common so we can store any record in this variable.
2. Parm method
First thing is to create a parm-method for this variable (created using parmFromCD editorscript):
Your code will be much cleaner and easier to debug when you use parameter methods.
3. New Method
Next, we will override the new method and make it protected:
Methods that are declared as protected can only be called from methods in the class and in subclasses of the class where the protected method is declared. When we want to create an instance of this class from an other class, we’ll have to call the construct method.
When calling the new() method in any other class, we would get the following compiler error:
The method is declared protected and may only be called from methods in classes derived from KLFShowRecordInfo.
4. Construct method
When using the editorscript to create a construct() method (Right click – Scripts – template – method – construct), it will look like this:
However, I always rewrite it like like this because it is easier to extend afterwards:
Now we’ll have to modify the construct method to receive a parameter, and use the parm method to set the variable in our class:
5. Run method
All we need now is some logic to add to this class. Most of the time, I name the method ‘run’, but you can give it any name you like. The method will display the name of the table of the record you pass to it.
6. Test job
Next, a job to test it:
You can see that we only need one line of code to call our class, and we don’t need a variable, which makes the code cleaner.
When creating a class, start with declaring the new method as protected. This will force you to use a static construct() method. This in turn will force you to think twice about the structure of your class, and will result in cleaner/better code with a more ‘AX-y’ feel.
In part 2, I will demonstrate how this design principle helps you to maintain your code when extending functionality.