Monday, March 14, 2016

Creating a C# construct that acts like a more complex switch/case

Inspired by my own post about simulating F# active patterns in C# and remembering an old crazy post about using try/catch to emulate a switch on types, I came up with this utility class that acts and looks like a switch statement, but can do a lot more. The basic idea was to use a fluent interface to get the same functionality of switch, but also add the possibility of using complex objects as case values or even code conditions.
an example of use

First, here is the source code:
namespace Constructs
{
    public static class Do
    {
        public static Switch<T> Switch<T>(T value)
        {
            return Constructs.Switch<T>.From(value);
        }
    }

    public class Switch<T>
    {
        private bool _isDone;
        private T _value;
        private Type _valueType;

        private Switch(T value)
        {
            this._value = value;
        }

        public static Switch<T> From(T value)
        {
            return new Switch<T>(value);
        }

        public Switch<T> Case(Func<T> valueFunc, Action<T> action, bool fallThrough = false)
        {
            if (_isDone) return this;
            return Case(valueFunc(), action, fallThrough);
        }

        public Switch<T> Case(T value, Action<T> action, bool fallThrough = false)
        {
            if (_isDone) return this;
            return If(v => object.Equals(value, v), action, fallThrough);
        }

        public void Default(Action<T> action)
        {
            if (_isDone) return;
            action(_value);
        }

        public Switch<T> If(Func<T, bool> boolFunc, Action<T> action, bool fallThrough = false)
        {
            if (_isDone) return this;

            if (boolFunc(_value))
            {
                action(_value);
                _isDone = !fallThrough;
            }

            return this;
        }

        private Type getValueType()
        {
            if (_valueType != null) return _valueType;
            if (object.Equals(_value, null)) return null;
            _valueType = _value.GetType();
            return _valueType;
        }

        public Switch<T> OfStrictType<TType>(Action<T> action, bool fallThrough = false)
        {
            if (_isDone) return this;
            if (getValueType() == typeof(TType))
            {
                action(_value);
                _isDone = !fallThrough;
            }
            return this;
        }

        public Switch<T> OfType<TType>(Action<T> action, bool fallThrough = false)
        {
            if (_isDone) return this;
            if (getValueType() == null) return this;
            if (typeof(TType).IsAssignableFrom(getValueType()))
            {
                action(_value);
                _isDone = !fallThrough;
            }
            return this;
        }
    }
}
I use the static class Do to very easily get a Switch<T> object based on a value, then run actions on that value. The Switch class has a _value field and an _isDone field. When _isDone is set to true, no action is further executed (like breaking from a switch block). The class has the methods Case, and If, as well as OfType and OfStrictType, all of which execute an action if either the value, the function, the condition or the type provided match the initial value. Default is always last, executing an action and setting _isDone to true;

Here is an example of use:
for (var i = 0; i < 25; i++)
{
    Do.Switch(i)
        .Case(10, v => Console.WriteLine("i is ten"), true)
        .Case(() => DateTime.Now.Minute / 2, v => 
            Console.WriteLine($"i is the same with half of the minute of the time ({v})"), true)
        .If(v => v % 7 == 0, v => Console.WriteLine($"{v} divisible by 7"))
        .Default(v => Console.WriteLine($"{v}"));
}
where the numbers from 0 to 25 are compared with 10, the half of the minutes value of the current time and checked if they are divisible by 7, else they are simply displayed. Note that the first two Case methods receive an optional bool parameter that allows the check to fall through, so that the value is checked if it is equal to 10, but also if it is twice the minute value or divisible by 7. On the other hand, if the value is divisible by 7 it will not display the value in the Default method.

Here is an example that solves the type check with the same construct:
var f = new Action<object>(x =>
    Do.Switch(x)
        .OfType<string>(v => Console.WriteLine($"{v} is a string"))
        .OfType<DateTime>(v => Console.WriteLine($"{v} is a DateTime"))
        .OfType<int>(v => Console.WriteLine($"{v} is an integer"))
        .OfType<object>(v => Console.WriteLine($"{v} is an object"))
);
f(DateTime.Now);
f("Hello, world!");
f(13);
f(0.45);

And finally, here is the solution to the famous FizzBuzz test, using this construct:
for (var i = 0; i < 100; i++)
{
    Do.Switch(i)
        .If(v => v % 15 == 0, v => Console.WriteLine($"FizzBuzz"))
        .If(v => v % 3 == 0, v => Console.WriteLine($"Fizz"))
        .If(v => v % 5 == 0, v => Console.WriteLine($"Buzz"))
        .Default(v => Console.WriteLine($"{v}"));
}

Now, the question is how does this fare against the traditional switch? How much overhead does it add if we would, let's say, take all switch/case blocks and replace them with this construct? This brings me to the idea of using AOP to check if the construct is of a certain shape and then replace it with the most efficient implementation of it. With the new Roslyn compiler I think it is doable, but beyond the scope of this post.

I have tried, in the few minutes that it took to write the classes, to think of performance. That is why I cache the value type, although I don't think it really matters that much. Also note there is a difference between Case(v=>SomeMethodThatReturnsAValue(),DoSomething()) and Case(SomeMethodThatReturnsAValue(),DoSomething()); In the first case, SomeMethodThatReturnsAValue will only be executed if the switch has not matched something previously, while in the second, the method will be executed to get a value and then, when the time comes, the switch will compare it with the initial value. The first method is better, with only 4 extra characters.

Hope it helps someone.

4 comments:

Andrei Ignat said...

Github?

Vlad Vizitiu said...

I second that request :)

Siderite said...

Is copy pasting the code too complicated for you, guys? :D

Andrei Ignat said...

YES