Monday, June 30, 2014

Generating decorator using ReSharper

Let’s say you have a class dealing with domain business stuff. Let’s call it IBusinessService. And one day you decide, that you would love to see the various results of this service in some statistics system/graph. The interface might look like this.

interface IBusinessService {
bool DoA();
bool DoB();
bool DoC();
}

Naive way to add monitoring/statistics to this code would be modifying every single implementation and adding statistics measuring code. Much better approach is creating a Decorator. Decorator basically calls underlying implementation and does anything with the result before returning it to the higher layer. There was a time when I accidentaly created an infinite loop in decorator, because when writing a decorator by hand, it is quite easy to write following (although ReSharper tries to point out this error by underlyin the bad call).

public bool DoA() {
return DoA();
}

instead of

public bool DoA() {
return UnderlyingService.DoA();
}

That was a reason why I have started to look for a way to generate the decorator instead of writing it by hand. Fortunately there is a way to do this .
First we need to let the ReSharper know we are actually implementing a Decorator.