11 October 2018

Set of responsibility

So, three and a half years later... I'm back.

According to wikipediathe chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects.[1] Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain.

In some cases, I will benefit from flexibility allowed by this pattern, without being tied to the chain-based structure, e.g. when there is an IoC container involved: Handlers in the pattern all have the same interface, so it's difficult to leave their instantiation to the IoC container.

In such scenario I use a variation of the classic chain of responsibility: there are still responsibilities, off course, but there is no chain out there.

I like to call my variation set of responsibility (or list of responsibility, see above for discussion about this) - the structure is the one that follows (C# code):

interface Handler {
    Result Handle(Request request);
  
    bool CanHandle(Request request);
}


class HandlerSet {
    IEnumerable handlers;

    HandlerSet(IEnumerable < handler > handlers) {
        this.handlers = handlers;
    }
 
    Result Handle(Request request) {
        return this.handlers.Single(h => h.CanHandle(request)).Handle(request);
    }
}

class Sender {
    HandlerSet handler;
 
    Sender(HandlerSet handler) {
        this.handler = handler;
    }

    void FooBar() {
        Request request = ...;
        var result = this.handler.Handle(request);
    }
}

One interesting scenario which I've applied this pattern in is the case in which the Handlers' input type Request hides a hierarchy of different subclasses and each Handler implementation is able to deal with a specific Request subclass: when use polymorphism is not a viable way, e.g. because those classes comes from an external library and are not under our control, we can use set of responsibility in order to cleanup the horrible code that follows:


class RequestX : Request {}

class RequestY : Request {}

class RequestZ : Request {}

class Sender {
    var result = null;
 
    void FooBar() {
        Request request = ...;
        
        if(request is RequestX) {
            result = HandleX((RequestX)request);
        } else if (request is RequestY) {
            result = HandleY((RequestY)request)
        } else if (request is RequestZ) {
            result = HandleZ((RequestZ)request)
        }
    }
}

We can't avoid is and () operators usage, but we can hide them behind a polymorphic interface, adopting a design than conform to open-closed principle:

class Sender {
    HandlerSet handler;
    Sender(HandlerSet handler) {
        this.handler = handler;
    }

    void FooBar() {
  Request request = ...;
     var result = this.handler.Handle(request);
    }
}

class HandlerX : Handler {
    bool CanHandle(Request request) => request is RequestX;
 
    Result Handle(Request request) {
        HandleX((RequestX)request);
    }
}

class HandlerY : Handler {
    bool CanHandle(Request request) => request is RequestY;
 
    Result Handle(Request request) {
        HandleY((RequestY)request);
    }
}

class HandlerZ : Handler {
    bool CanHandle(Request request) => request is RequestZ;
 
    Result Handle(Request request) {
        HandleZ((RequestZ)request);
    }
}

Adding a new Request subclass case is now only a matter of adding a new HandlerAA implemementation of Handler interface, without the need to touch existing code.

I use in cases like the explained one the name of set of responsibility to stress the idea that only one handler of the set can handle a single, specific request (I use _handlers.Single(...) method in HandlerSet implementation, too).

When the order in which the handlers are tested matters, we can adopt a different _handlers.Single(...) strategy: in this case I like to call the pattern variation list of responsibility.

When more than one handler can handle a specific request we can think to variations of this pattern that select all applyable handlers (i.e. those handlers whose CanHandle method returns true for the current request) and apply them to the incoming request.

12 August 2015

Embrace change

So it is: three months ago I joined a new job position, switching from a big company to a little, agile one, after more than eight years of distinguished service :-).
Furthermore: I switched from a Java and JEE - centric technological environment to a more rich and various one - yet .NET and C# oriented.
So, my Java Peanuts will maybe become in the future C# Peanuts (or Node.js Peanuts, who knows...) or, more generally, Programming Peanuts: for the moment I'm still planning a little post series about my way from Java to .NET, so... if you are interested... stay tuned!

22 July 2014

Seven things I really hate in database design

  1. Common prexif in all table names
    1. es: TXXX, TYYY, TZZZ, VAAA, VBBB - T stays for Table, V stays for View
    2. es: APPXXX, APPYYY, APPZZZ - APP is an application name
  2.  Common prefix in all field names in every table
         es: APPXXX.XXX_FIELD_A, APPXXX.XXX_FIELD_B, APPXXX.XXX_FIELD_C
  3. Fields with the same meaning and different names (in different tables)
         es: TABLE_A.BANK_ID, TABLE_B.BK_CODE
  4. Fields with the same logical type and different physical types
          es: TABLE_A.MONEY_AMOUNT NUMBER(20,2)
          TABLE_B.MONEY_AMOUNT NUMBER(20,0) -- value * 100
          TABLE_B.MONEY_AMOUNT VARCHAR(20) --value * 100 as char
  5. No foreign-keys nor integrity constraints at all - by design
  6. Date (or generally structured data type) representation with generic and not specific types
    1. es: TABLE_A.START_DATE NUMBER(8,0) -- yyyyddmm as int
    2. es: TABLE_B.START_DATE VARCHAR(8) -- yyyyddmm as char
  7.  (possible only in presenceof 6.) Special values for semantic corner-cases which are syntactically invalid
          es: EXPIRY_DATE = 99999999 -- represents "never expires case",
       but... IT'S NOT A VALID DATE!!! - why not 99991231??

29 October 2012

Automate JavaScript testing

I like TDD and testing automation and I'm used to consider essential a toolset providing automation for unit, integration, system tests and for code coverage analysis.

Switching from Java to JavaScript development, I tried to put together a Maven-based toolset that resembles the classic automation tools for Java: a testing framework (with a runner which I can run through mvn clean test) and a code coverage tool (which I can for example run through mvn verify, obtaining a graphical coverage report).

The result is this small example of JavaScript library, whose Maven-based automation is achieved through a number of excellent frameworks (Jasmine) and Maven plugins (Jasmine Maven Plugin, Saga JS coverage plugin).

Feel free to checkout my sample and to adjust it to your needs!

29 May 2012

Mocking static methods and the Gateway pattern

A year ago I started to use mocking libraries (e.g., Mockito, EasyMock, ...), both for learning something new and for testing purpose in hopeless cases.
Briefly: such a library makes it possible to dynamically redefine the behaviour (return value, thrown exceptions) of the methods of the class under test, in order to run tests in a controlled environment. It makes it possible even to check behavioural expectations for mock objects, in order to test the Class Under Test's interactions with its collaborators.
A few weeks ago a colleague asked me: "[How] can I mock a static method, eventually using a mock library?".
In detail, he was looking for a way to test a class whose code was using a static CustomerLoginFacade.login(String username, String password) method provided by an external API (an authentication custom API by a customer enterprise).
His code looked as follows:

public class ClassUnderTest {
  ...
 public void methodUnderTest(...) {
  ...
   // check authentication
   if(CustomerLoginFacade.login(...)) {
      ...
  } else {
    ...
   }
 }
}

but customer's authentication provider was not accessible from test environment: so the main (but not the only: test isolation, performances, ...) reason to mock the static login method.

A quick search in the magic mocking libraries world revealed that:
  • EasyMock supports static methods mocking using extensions (e.g, Class Extension, PowerMock)
  • JMock doesn't support static method mocking
  • Mockito (my preferred [Java] mocking library at the moment) doesn't support static method mocking, because Mockito prefers object orientation and dependency injection over static, procedural code that is hard to understand & change (see official FAQ). The same position appears even in a JMock-related discussion. PowerMock provides a Mockito extension that supports static methods mocking.
So, thanks to my colleague, I will analize the more general question "Ho can I handle external / legacy API (e.g., static methods acting as service facade) for testing purposes?". I can identify three different approaches:
  • mocking by library: we can use a mocking library supporting external / legacy API mocking (e.g, class' mocking, static methods' mocking), as discussed earlier
  • mocking by language: we can refer to the features of a dynamically typed programming language to dynamically change external / legacy API implementation / behaviour. E.g., the login problem discussed earlier can be solved in Groovy style, using the features of a language fully integrated with the Java runtime: 
CustomerLoginFacade.metaClass.'static'.login = {
              return true;
}; 

Such an approach can be successfully used when CustomerLoginFacade.login's client code is Groovy code, not for old Java client code.
  • Architectural approach: mocking by design. This approach refers to a general principle: hide every external (concrete) API behind an interface (i.e.: coding on interfaces, not on concrete implementation). This principle is commonly knows as dependency inversion principle.
So, we can solve my colleague's problem this way: first, we define a login interface:

public interface MyLoginService {
 public abstract boolean login(final String username, final String password);
}

Then, we refactor the original methodUnderTest code to use the interface:

public class ClassUnderTest {
  private MyLoginService loginService;
 // Collaborator provided by Constructor injection (see here for
 //  a discussion about injection styles)
 public ClassUnderTest(final LoginService loginService) {
  this.loginService = loginService;
 }   
 ...
 public void methodUnderTest(...) {
  ...
   // check authentication
   if(loginService.login(...)) {
      ...
  } else {
    ...
   }
 }
}


So, for testing pourposes, we can simply inject a fake implementation of the MyLoginService interface:

public void myTest() {
 final ClassUnderTest cut = new ClassUnderTest(new FakeLoginService());
 cut.methodUnderTest(..., ...);
 ...
}


where FakeLoginService is simply
 
public class FakeLoginService implements MyLoginService {
 public boolean login(final String username, final String password) {
  return true;
 }
}

and the real, pruduction implementation of the interface looks simply like this:

public class RealLoginService implements MyLoginService {
 public boolean login(final String username, final String password) {
  return CustomerLoginFacade.login(username, password);
 }
}


Ultimately, the interface defines an abstract gateway to the external authentication API: changing the gateway implementation, we can set up a testing environment fully decoupled from real customer' authentication provider
.
IMHO, i prefer the last mocking approach: it's more object oriented, and after all... my colleague called me once the more OO person I know :-). I find this approach more clean and elegant: it's built only upon common features of programming languages and doesn't refer to external libraries nor testing-oriented dynamic languafe features.
In terms of design, too, I think it's a more readable and more reusable solution to the problem, which allows a clearer identification of responsibilities of the various pieces of code: MyLoginService defines an interface, and every implementation represents a way to implement it (a real-life (i.e.: production) implementation versus the fake one).

However, method mocking (by library or by language, doesn't matter) is in certain, specific situations a very useful technique, too, especially when code that suffers static dependencies (ClassUnderTest in our example) is an example of legacy code, designed with no testing in mind, and is eventually out of developer control.
[Incidentally: the solution adopted by my colleague was just that I have proposed (i.e., mocking by design)]

Credits: thanks to Samuele for giving me cause to analyze such a problem (and for our frequent and ever interesting design-related discussion). Thanks to my wife for hers valuable support in writing in pseudo-English