Strategy decorator

Printer-friendly versionPrinter-friendly version
Decorators over strategies

 

Class Diagram I Drawbacks

Remember the saying

There ain't no such thing as a free lunch

This design has the following potential drawbacks:

  • The behavior of an application might be less comprehensible, if decorators are added to the strategy anywhere in the middle of the business code instead of adding them at specific places.
    • To prevent this, introduce a separate interface for the strategy decorators that extends the strategy. This decouples the usage of the strategy from the decoration of the strategy. See next diagram.
  • For each operation that returns a value it has to be clear how a decorator shall handle the value from the decorated strategy to be consistent with other decorators.
    • To achieve this, comment the operations in the strategy interface where needed, e.g. in Java use Javadocs or custom Annotations for that. For instance specify if the value from the decorated strategy should be dropped or used for further calculations.
    • Moreover, it should be avoided that the behavior of a decorator for a certain operation logically depends on the behavior of another decorator. In cases where it cannot be avoided, the decorator should only implement operations depending on the same behavior.
  • The code of a long chain of decorators might not be formatted nicely by the IDE out of the box, but on the other hand it should be simple to circumvent that issue.
    • To circumvent that issue, turn off the formatting for these lines and format manually. Popular IDE like Eclipse and IntelliJ support tags for that („// @formatter:off“, „// @formatter:on“) or turn off the formatting for each line by a following double slash („//“).

 

Class Diagram II  with decorator interface

 

Class Diagram II Benefits

This design prevents that developers are tempted to add decorators to the strategy anywhere in the middle of the business code. Instead, decorators will be added to the strategy at specific places only, typically at the beginning of the process. Thus, we know where in the code we can analyze the behavior that has been added with strategy decorators.

 

Pages