I have a style of programming that generally works well for me. I like to solve a problem and then step back and evaluate my solution. This gives me a chance to see if there is a better way to solve the problem at hand. In the programming world we gave this a fancy name, refactoring. I am also very lucky to have some really smart people at work so when I have the chance to discuss code I take it.
Last week I was working on a problem that I have solved countless times before. I had an array of objects and I wanted to make sure no duplicates of a certain key were returned to the caller. Before I write some code I like to talk the solution out so in plain English this is what I need to do.
- create an empty array to hold our new array
- loop over our existing array of objects
- if the current key doesn't exist in our new array, add it
Seems pretty simple and I am betting a lot of people have taken this approach before. So what does this look in code? First we have our example array of objects. In this array class code is the key we don't want to duplicate. Next we create an empty array that will contain our duplicate free result. Next we are going to loop over our array. During each iteration we loop through our new array and check to see if that value exists, if it does not go ahead and add this object to the new array.
While this works great I was talking with a coworker (Jason Delmore) and he came up with a pretty cool alternative. Instead of creating a new array to hold our result we can simply look ahead to see if this key exists and if it does remove it and decrement the loop index.
This may seem like a small change or there may be better ways to solve this (I would love to hear them) but I love it. I enjoy looking at problems like this and understanding ways to solve them (in English) and then taking a look at how we can implement them.