Friday, November 2, 2012

Design Patterns in AX - Strategy Design Pattern

Design Patterns help developers solve recurring complex problems in their code. We see lot of inheritance getting used in AX code. Inheritance is a good OOPS concept and helps in writing smart code. But only to an extent. In some situations, code becomes too deep, too hard to maintain, debug or upgrade. That's when design patterns come to the rescue. The Gang of Four (GOF) introduced the concept of Design Patterns in their book
There are a total of 23 patterns in the book.

I always wanted to write on this topic and this post will cover one of the patterns - Strategy Design Pattern. Quoting from the GOF book, the Strategy design pattern is defined as “Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.”
I will use some sample AX code to supplement my post.

1. First we define our interface class named Strategy with one method algorithm.

 2. Then we define three concrete classes aptly named ConcreteStrategyA, ConcreteStrategyB and ConcreteStrategyC with their implementations of method algorithm.

3. Next we have a class StrategyContext which is actually a pass through class whose working we will see shortly in the job.

4. Finally we define the job. We initialize the three concrete classes, define a switch case, call the contextInterface method and depending on the value in the variable condition, algorithm method of the corresponding concrete class is called.

5. The Infolog.

The Strategy Design Pattern says that you should extract the volatile parts of your code and encapsulate them as objects; you can use those objects as you need them. You can customize your code by creating composites of objects. At runtime, you just use polymorphism to choose the object(s) you want to work with. Feel free to ask me for the xpo. I will be posting more posts on this topic.

No comments:

Post a Comment