Code Monkey home page Code Monkey logo

responsibilitychain's Introduction

Chain of Responsibility and Composite pattern combined

Build status Nuget netstandard

Frameworks and platforms support

  • .NET Core 1.0
  • .NET Framework 4.5
  • Mono 4.6
  • Xamarin.iOS 10.0
  • Xamarin.Mac 3.0
  • Xamarin.Android 7.0
  • Universal Windows Platform 10.0
  • Unity 2018.1

Usage

Step 1: Declare

Handlers should implement IHandler<TIn, TOut> interface

public interface IHandler<TIn, TOut>
{
    TOut Handle(TIn input, Func<TIn, TOut> next);
}

Example

/// <summary>
///     Parses work log to minutes.
///     E.g. "30m" => 30 minutes
/// </summary>
public class MinuteParser : IHandler<string, int>
{
    private readonly Regex _pattern = new Regex("^(\\d+)m$");

    // implement IHandler<TIn, TOut>.Handle method
    public int Handle(string input, Func<string, int> next)
    {
        if (!_pattern.IsMatch(input))
        {
            // current handler cannot handle the input, so pass it to the next handler
            return next.Invoke(input);
        }

        // parse and return number of minutes
        // ...
        return minutes;
    }
}

Step 2: Compose

A composite handler then extends Handler<TIn, TOut> abstract class and add child handlers via its constructor

public class WorkLogParser : Handler<string, int>
{
    public WorkLogParser(WorkLogValidator validator, IndividualUnitParser individualUnitParser)
    {
        AddHandler(validator);
        AddHandler(individualUnitParser);
    }
}

A composite handler can have as many nested handlers as needed. Support for deeply nested handlers is a natural progression.

var parser = new WorkLogParser(
    new WorkLogValidator(
        new WorkLogMustNotBeNullOrEmptyRule(),
        new ThereShouldBeNoUnitDuplicationRule(),
        new UnitsMustBeInDescendingOrderRule()
    ),
    new IndividualUnitParser(
        new WeekParser(),
        new DayParser(),
        new HourParser(),
        new MinuteParser()
    )
);

Step 3: Execute

// work log in minutes
int workLog = parser.Handle("1w 2d 4h 30m");

Assert.Equal(3630, workLog);

Notes

If the last handler in the chain cannot handle the input (and it passes the input to the next handler), the composite handler will throw an exception of type NotSupportedException by default. This can be made explicitly via chain's constructor

public class WorkLogParser : IHandler<string, int>
{
    public WorkLogParser(
        WorkLogValidator validator,
        IndividualUnitParser individualUnitParser,
        ThrowNotSupported<string, int> throwNotSupported)
    {
        AddHandler(validator);
        AddHandler(individualUnitParser);

        // explicitly tell the chain to use ThrowNotSupported as the last resort
        AddHandler(throwNotSupported);
    }
}

or via method invocation

var workLog = parser.Handle("1w 2d 4h 30m", new ThrowNotSupported<string, int>().Handle);

There are also other built-in last resort handlers

  • ReturnDefaultValue
  • ReturnCompletedTask
  • ReturnCompletedTaskWithDefaultValue

Asynchronous operation

For asynchronous operations, handlers should implement IAsyncHandler<TIn, TOut>

public interface IAsyncHandler<TIn, TOut> : IHandler
{
    Task<TOut> HandleAsync(TIn input, Func<TIn, CancellationToken, Task<TOut>> next, CancellationToken cancellationToken);
}

responsibilitychain's People

Contributors

son-nd-niteco avatar sonbua avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

responsibilitychain's Issues

All nested handlers and their dependencies should be injected via constructor

Framework currently supports in resolving dependencies via an injected IServiceProvider instance in the composite handler's constructor like this

public class WorkLogParser : Handler<string, int>
    public WorkLogParser(IServiceProvider serviceProvider) : base(serviceProvider)
    {
        AddHandler<NestedHandler1>();
        AddHandler<NestedHandler2>();
    }
}

This makes SUT (WorkLogParser) hard to test in case one wants to mock out a nested handler (such as logging, database access,...) or a dependency of a nested handler.
So a handler (and composite handler) should expose all dependencies via constructor parameters instead of the service locator anti-pattern.

public class WorkLogParser : Handler<string, int>
    public WorkLogParser(NestedHandler1 nestedHandler1, NestedHandler2 nestedHandler2)
    {
        AddHandler(nestedHandler1);
        AddHandler(nestedHandler2);
    }
}

Should be able to cancel an asynchronous operation

Current IAsyncHandler<TIn, TOut> definition:

public interface IAsyncHandler<TIn, TOut> : IHandler
{
    Task<TOut> HandleAsync(TIn input, Func<TIn, Task<TOut>> next);
}

HandleAsync(), once started, couldn't be cancelled.

It should look like this:

public interface IAsyncHandler<TIn, TOut> : IHandler
{
    Task<TOut> HandleAsync(TIn input, Func<TIn, CancellationToken, Task<TOut>> next, CancellationToken cancellationToken);
}

Have a `Handle` method, which accepts `input` object only and no `next` delegate

This is the current interface definition of IHandler<TIn, TOut> and IAsyncHandler<TIn, TOut>

public interface IHandler<TIn, TOut> : IHandler
{
    TOut Handle(TIn input, Func<TIn, TOut> next);
}

public interface IAsyncHandler<TIn, TOut> : IHandler
{
    Task<TOut> HandleAsync(TIn input, Func<TIn, Task<TOut>> next);
}

When client consumes this API via a composite handler, she often has to pass null as the next handler. This is inconvenient and adds noise to the code base. Having an additional Handle method on the abstract composite, which requires the input object only and no next delegate, improves readability.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.