Monday 28 November 2011

Functional composition, fluent programming and command line processing

We have a very repetitive and, to me, offensive piece of code which appears in several places throughout the codebase. The only variation between instances are the names of the parameters and the decision about which ones are mandatory. So I wrote some nice simple, functional code to do the heavy lifting, and now it's a one-liner, more or less!

            string defaultDate = DateTime.Today.ToShortDateString();
            const string defaultCheckType = "pnl";
            
            Dictionary<string, string> mandatoryArgs = Functional.array.toDict(new string[] { "filedir" });
            Dictionary<string, string> optionalArgs = Functional.array.toDict(new string[] {"interfaces", "filename", "reportingdate", "check"},
                                                                              new string[] { string.Empty, string.Empty, defaultDate, defaultCheckType });

            bool result = args > SplitArgsInto(mandatoryArgs, optionalArgs).Then(Validate(mandatoryArgs));

            return new Arguments(mandatoryArgs["filedir"], 
                                    optionalArgs["filename"],
                                    DateTime.ParseExact(optionalArgs["reportingdate"], "dd/MM/yyyy", CultureInfo.InvariantCulture),
                                    (CheckTypeEnum) Enum.Parse(typeof (CheckTypeEnum), optionalArgs["check"]), 
                                    optionalArgs["interfaces"]);

Lovely! Now the arguments are split into mandatory and optional, the mandatory arguments have all been validated and the program receives by return a structure containing the names and values that are relevant. Smashing!

In case you were wondering, the functional composition is hidden in the Then function, which is actually the composition operator in C# land. It takes Func<A,B>, Func<B,C> and returns Func<A,C>.