Craftsman at Work

I'm Artur Karbone, coding software architect and independent IT consultant and this is my blog about craftsmanship, architecture, distributed systems, management and much more.

Substitute 'ifs' With Message Passing

I've just watched yet another stellar talk by Sandi Metz, called Nothing is Something (RailsConf 2015). In the talk Sandi was presenting how to substitute if statement with message passing, leverage Null Object pattern, prefer composition over inheritance to share behavior.

Just want to make a quick concept here, substitute if with message passing in C# and push it to GitHub.

Let's start.

The traditional way to control flow via if statement:

private static void Test1(bool condition)  
        {
            Console.WriteLine("Test1");
            if (condition)
            {
                Console.WriteLine("That's true");
            }
            else
            {
                Console.WriteLine("That's false");
            }
        }

What we want to achieve here is to extend Boolean class, so it can accept messages to handle true/false scenarios. These methods/messages are going to accept a lambda as a parameter.

public static class BoolExtensions  
    {
        public static void IfTrue(this bool value, Action action)
        {
            if (value)
            {
                action();
            }
        }

        public static void IfFalse(this bool value, Action action)
        {
            if (!value)
            {
                action();
            }
        }
    }

Let's try it out now:

static void Main(string[] args)  
        {
            GatherConditions()
                .ToList()
                .ForEach(condition =>
                {
                    Test1(condition);
                    Test2(condition);
                });

            Console.ReadLine();
        }

        static IEnumerable<bool> GatherConditions() {
            yield return 1 == 1;
            yield return 1 == 2;
        }


        private static void Test1(bool condition)
        {
            Console.WriteLine("Test1");
            if (condition)
            {
                Console.WriteLine("That's true");
            }
            else
            {
                Console.WriteLine("That's false");
            }
        }

        private static void Test2(bool condition)
        {
            Console.WriteLine("Test2");
            condition.IfTrue(() => Console.WriteLine("That's true"));
            condition.IfFalse(() => Console.WriteLine("That's false"));            
        }

This code is available in GitHub

The Summary

There are many ways to control application's flow besides ifs and switch. Like message passing discussed in this particular article or Pattern Matching in functional languages.

comments powered by Disqus