Posts RSS Comments RSS 25 Posts and 50 Comments till now

SafeMap

Axapta’s Map data structure is something I use quite often. Maps, Set, List, Array and Struct may not be very well known data types but I prefer them over the often abused container.

Unfortunately Maps throw errors when you call lookup() with a key that doesn’t exist. Throwing an exception is a valid way of handling the situation but as I showed earlier, this can be a problem. The remedy is simple, check the key first with the exists() method. This however places a burden on the user of the map. Before you know it your code is littered with checks and that simple interface with a 3rd party system gets tedious to write.


    Map map = new Map(Types::String, Types::String);
    //...
    palletId = map.exists('Pallet')  ? map.lookup('Pallet')  : '';
    serialId = map.exists('Serial')  ? map.lookup('Serial')  : '';
    itemId   = map.exists('Product') ? map.lookup('Product') : '';
    // and so on ...

That’s not so easy to read and maintain. I finally got fed up with the duplication and wrote a simple Map subclass to do this checking for me: SafeMap. It’s safe because it doesn’t throw an exception. I guess you could consider that behaviour unsafe as well.

But what if the value doesn’t exist? Surely, lookup()can’t return a value. Yes it can. It returns the default null value for the map value type. Code that doesn’t care about the failed lookup, probably wants the null value anyway. And just in case the user of SafeMap needs to know if the lookup succeeded, there is a lookupOk() method. It simply returns a boolean that indicates if the last lookup succeeded or not.

The above code now becomes:


    Map map = new SafeMap(Types::String, Types::String);
    //...
    palletId = map.lookup('Pallet');
    serialId = map.lookup('Serial');
    itemId   = map.lookup('Product');

Much clearer, don’t you think?

After discovering the testing framework in Dynamics Ax 4.0 I decided to upgrade (read: export from 3.0 and import in 4.0 :) ) and at the same time throw in a very simple test class as an example. Check out David Pokluda’s SysTest quick start for more information about the framework.

SafeMap.xpo (Dynamics Ax 4.0)

Trackback this post | Feed on Comments to this post

Leave a Reply