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...
at this point someone pointed out the ?? operator...
It's worth noting that if your language has 'truthiness' (like javascript) you can also do this with the or (||) operator
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 niceIt'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?
Which one do you like?
4 comments:
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
https://gist.github.com/JayBazuzi/cea91f55a8ff2d117ea537fa7914d9ef
Option 4a: as long as you have a `DoIfNull()` method, just inline the use of the local: https://gist.github.com/JayBazuzi/c93ac3f8da87983b0d8a1896160fda97
I like #5 (chained `??`) the best.
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.
Post a Comment