Saturday, July 30, 2016

5 ways to do Decision trees in C#

At Agile2016 we spent the mornings doing Mob Programming working on the Tennis Refactoring Kata from Emily Bache.

Thursday we ran accross this issue:

#1. If Structure

This is fairly easy to code as is, the trouble is it looks horrible:

So we started to play around with alternative structures...

#2. Pass in result

One solution is to call all the methods but abort early if you've already found a solution.
This looks a lot nicer, the problem is it leaks into the underlying methods
So we keep looking..

#3. Linq

If you like linq you can solve this with a bit of functional code

This reads nicely, but is a bit confusing as to why it works and means all your methods must not use any parameters.

but It can also be used with the yield keyword, which is neat and allows parameters but splits logic.
so we kept looking...

#4. Do If Null

We were able to get closer to the 'Pass in result' without leaking with the addition of an extension method.
at this point someone pointed out the ?? operator...

#5. ?? Operator

The ( a ?? b ) operator says if  a is null do b. The resulting code is rather nice
It's worth noting that if your language has 'truthiness' (like javascript) you can also do this with the or (||) operator

Which is Best?

Of course that's up to you. For us most liked the ?? operator best, while a few thought the Linq solution was the nicest.

Which one do you like? 


Jay Bazuzi said...

Option 1a: invert the `if`s and save the results. Not sure if it's better or worse than #1, but it's a little shorter.

1a: invert the if. Not clear if it's better or worse, but some people might

Option 4a: as long as you have a `DoIfNull()` method, just inline the use of the local:

I like #5 (chained `??`) the best.

Henrik Ebbeskog said...
This comment has been removed by the author.
Henrik Ebbeskog said...
This comment has been removed by the author.
Chris Lucian said...

I had a lot of fun at #Agile2016 and this was a great way to start the morning. Highly recommended kata for people looking into Legacy Refactoring and Mob Programming.