19 February 2019

Set Of Responsability and IOC

I recently read this Pietro’s post about a possible adaptation of the “Chain of responsability” pattern: the “Set of responsability”. This is very similar to its "father" because each Handler handles the responsibility of a Request but in this case it doesn’t propagate the check of responsibility to other handlers. There is a responsibility without chain!

In this article I’d like to present the usage of this pattern in an IOC Container, where the Handlers aren’t added to the HandlerSet list but provided from the container. In this way you can add new responsibility to the system simply adding a new Handler in the container without changing other parts of implemented code (es. the HandlerSet), in full compliance with the Open closed principle.  

For coding I’ll use the Spring Framework (JAVA) because it has a good IOC Container and provides a set of classes to manage with that. Inversion of control principle and the Dependency Injection are first class citizens in the SpringFramework.

Here is the UML class diagram with 3 responsabilities X,Y,Z and a brief description of the solution adopted.

@Component
public class XHandler implements Handler {

    @Override
    public Result handle(Request request) {
       return ((RequestX) request).doSomething();
    }

    @Override
    public boolean canHandle(Request request) {
        return request instanceof RequestX;
    }
} 
@Component annotation on XHandler tells to Spring to instantiate an object of this type in the IOC container.
public interface HandlerManager {
    Result handle(Request request) throws NoHandlerException;
}
@Service
public class CtxHandlerManager implements HandlerManager {

    private ApplicationContext applicationContext;

    @Value("${base.package}")
    private String basePakage;

    @Autowired
    public CtxHandlerManager(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public Result handle(Request request) throws NoHandlerException {
        Optional handlerOpt = findHandler(request);
        if ( !handlerOpt.isPresent() ) {
            throw new NoHandlerException();
        }
        Handler handler = handlerOpt.get();
        return handler.handle(request);
    }

    private Optional<Handler> findHandler(Request request) {
        ClassPathScanningCandidateComponentProvider provider = createComponentScanner();

        for (BeanDefinition beanDef : provider.findCandidateComponents(basePakage)) {
            try {
                Class clazz = Class.forName(beanDef.getBeanClassName());
                Handler handler = (Handler) this.applicationContext.getBean(clazz);
                //find responsible handler for the request
                if (handler.canHandle(request)) {
                    return Optional.ofNullable(handler);
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        return Optional.empty();
    }

    private ClassPathScanningCandidateComponentProvider createComponentScanner() {
        ClassPathScanningCandidateComponentProvider provider
                = new ClassPathScanningCandidateComponentProvider(false);
        provider.addIncludeFilter(new AssignableTypeFilter(Handler.class));
        return provider;
    }
}
CtxHandlerManager works like an Handler dispatcher.  The handle method finds the Handler and calls its handle method  which invokes the doSomething method of the Request.

In the findHandler method I use the Spring ClassPathScanningCandidateComponentProvider object with an AssignableTypeFiler to the Handler class. I call the findCandidateComponent on a basePackage (the value is set by @Value Spring annotation) and for each candidate the canHandle method check the responsability. And that's all!

In Sender class the HandlerProvider implementation (CtxHandlerManager)is injected by Spring IOC by "Autowiring":


@Service
public class Sender {

    @Autowired
    private HandlerManager handlerProvider;

    public void callX() throws NoHandlerException {
        Request requestX = new RequestX();
        Result result = handlerProvider.handle(requestX);
        ...
    }

This solution let you to add new responsibility simply creating new Request implementation and a new Handler implementation to manage it.  By applying @Component annotation on the Handler you allow Spring to autodetect the class for dependency injection when annotation-based configuration and classpath scanning is used. On application reboot, this class can be provided by the IOC Container and instantiated simply invoking the HandlerManager.

In the next post I’d like present a possible implementation of a Component Factory using the "Set of responsability" pattern in conjunction with another interesting pattern, the "Builder pattern".


Happy coding   
Mauro

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!