know your
collection api

Loop through your collection API

A few days ago I was implementing a new feature in some good and old legacy codebase. When I got a little bit surprised by a method containing lots of lines of code. At the first glance, I couldn't understand much what was going on, so many variables going everywhere a bunch of ifs and elses blocks flying around.

But suddenly I came across a code a piece of code such as the following:

object = nil

value = 'some_value'

collection = [object1, object2, object3]

collection.each do |obj|
  if obj.include?(value)
    object = obj

We have around 9 lines of code

When you come across this kind of code, where you have a variable being set to nil, then you have a loop through some collection, and the variable is being used inside of it for some reason. I could say that you have a little smelly code, plus who wrote it doesn't have enough knowledge about the programming language (ruby in this particular case) collection API.

I would recommend you, whatever the language you are using if you have to iterate over a collection and return something for from this collection. Stop a little bit, and go read the docs. Don't need to read it until you know every method or every implementation by heart. But give a good read, and try to at least memorize some of the methods names. I bet you will thank me in the future for that.

Improving the codebase

As far as I could understand, this piece of code just wanted to return the first object the match a given value. At the moment I realize that I remembered the #detect method.

value = 'some_value'

collection = [object1, object2, object3]

object = collection.detect { |obj| obj.include?(value) }

Now we are down to 3 lines of code, and a more readable code

Have you read your collection API today? Go for it, just remember one thing. If you are a JavaScript fan, read the docs from MDN, and please avoid W3Schools (or should I say W3Fools?) at all costs. Better be safe, than sorry. If you have any thoughts about it, let me know. You can find my info clicking here.