I’ve recently been writing a lot of lazy functional code in C# that allows for better re-usability and cleaner solution than it would have been if it had been written in an Object Oriented manner. This also helped in lower level code by focusing on steps to solve a problem rather than worrying about scoping and sequence of execution.

What I had come to realise whilst writing lots of code using generators is how much it helps me solve problems in effective ways.

Okay. Enough talk. Let’s see some code.

Let’s try to parse an array of string into an integer, when successfully parsed, it is add it to a dictionary with key starting from 0 incrementing by 1 each time an Key Value pair is added.

Here is an imperative approach to solve this:

1
2
3
4
5
6
7
8
9
10
11
12
var strs = new[] { "not a valid number", "1", "2", "3" };
IDictionary<int, int> dict = new Dictionary<int, int>();
int i = 0;
foreach (var str in strs)
{
    int num = 0;
    if (int.TryParse(str, out num))
    {
        dict.Add(i, num);
        i++;
    }
}

Here is a more functional approach using LINQ / generators:

1
2
3
4
5
6
var strs = new [] { "not a valid number", "1", "2", "3" };
int num = 0;
var i = 0;
var dict = strs
    .Where(x => int.TryParse(x, out num))
    .ToDictionary(x => i++, x => num);

The things to notice here apart from the reduced number of lines of code required is the actual thought process required to solve the same problem.

With the imperative approach, we had to think about where to place certain statements so that our key incrementation happens (line 10) only when we add an item to a dictionary. This could easily be misplaced elsewhere such as the end of our foreach loop.

With the functional approach, most of the thinking was concerned about solving the actual problem rather than the sequence of execution at a micro-level. We had to think what makes a valid number (WHERE), and what do we do after that (Turn the set into a dictionary with incrementing key from 0).

I think, over the years, I have come to take certain things for granted. As a Developer, I try to be pragmatic with my approach, I do not use any particular tool, paradigm, guideline or principle as gospel, I pick what works for the problems that I have.

I am a firm believer that in order to be a good Developer, we need to have a great understanding of how tools, paradigms, guidelines or principles help us solve our problems. Being able to understand the underlying fundamental principles behind the things that we use also allows us to apply this knowledge in other aspects of Software Development (or even beyond it).

Next time you think something seems trivial, think - are there other possible solutions? why does your approach make it easier for you? Can this approach be applied in other ways?

Thanks for dropping by :)