Code Kata 2 Day 4

So no witty reference today in the title. I just don’t have one. What I do have is a new solution to Code Kata 2. In this solution, I will use the function built into generics. I think this may be my most elegant solution. So I am pretty happy with this one. Lets dig into it.

Whoa, buddy, I have not gotten to say anything snarky about Code Kata 2 Day 4 and that is unacceptable.

Sorry, sometimes the world is not your oyster and the IT gods demand some code review.

Day4Chop.cs

using System;
using System.Collections.Generic;
namespace CodeKata2
{
   public class Day4Chop
   {
      public int chop(int numberToSeek, List intList)
      {
         int? foundNumber = intList.FindIndex(i => i == numberToSeek);

         if(foundNumber == null) 
         { 
            return -1; 
         } 
     
         if (foundNumber.HasValue) 
         { 
            return foundNumber.Value; 
         } 

          return -1; 
      } 
   }
}

Is this code perfect? No, I would like to have fewer checks in it but it is not too bad. It is a really good length. Lots of white space and everything is reasonably named.

This code really benefits about using nullable types. If you don’t know about them, that is what the ? at the end of the type declaration did. I simply have the list give me the index of the array with the… I think that is technically a lambda expression. It’s using its operator. I can’t believe I forgot the technical stuff. Anyway, I am going to call it a lambda since I think the => is the lambda operator. Do the lambda expression to check for equality to the number we check. The rest is mostly making sure that things are not null and have a value. If they do have a value return that index.

I will say in refactoring, I would change foundNumber into foundIndex to make things clearer.

I would also check to see if a null exception get thrown if I had a null then checked its HasValue property. Since this was a type it sort of thing rather than a more planned build, I just did the null check cause that is how I roll. I am 90% sure I don’t need the null check.

Finally, if everything else does not return then return the -1.

Of my implementations, I think this is my favorite. At least, a bunch more than yesterday’s solution. Tomorrows will be a asynchronous example and I suspect I am not going to be as impressed with it as I am with this one.

So if you liked Code Kata 2 Day 4 then you will really love Code Kata 2 Day 5. I built it up so well in the previous paragraph. This one may have been just a little too honest during the stream of consciousness writing. But here it is anyway.

Leave a Reply

Your email address will not be published.