Thursday 11 February 2016

X++ in AX7: Static members

You can now declare class member variables as static. The semantics are exactly the same as in C#; namely that all instances of the class will share the member, e.g. if one class sets the value, another class can get it.

Naturally; this should be used with care, but there are some really cool use cases, for example, implementing a singleton pattern in now much cleaner.

Example:
class MyClass
{  
    static MyClass singleton;

    public MyClass getInstance()
    {
        if (!singleton)
        {
            singleton = new MyClass();
        }
        return singleton;
    }
}     

In previous versions of AX you could achieve similar behavior through the SysGlobalCache classes. The main functional difference between the two is that you can flush the SysGlobalCache classes.




This is especially useful during test execution, where the test framework is automatically flushing the caches between each run to avoid state leaking from one test to another.




Static members will not automatically be flushed – you can of course create a flush() method yourself and hook it up to the SysTest::postInvokeTearDown() event.

No comments:

Post a Comment