The Nested Loop Nightmare

Bad code holds a strong position in the list of things I hate. Ruby is a beautiful language which you can write efficient, readable and beautiful code. But some developers are so talented cooks, they make ruby-spaghetti. But yesterday I was knee deep in some bad code.

I opened a huge module that had over 1000 lines of code that handled the import/update of resources using 4 remote services. I was like “hmm… this guy needs OOP lessons”. When I looked in to a method that handled one resource I noticed it was 200+ lines with no comments and cryptic code. It had 5 loops in 3 levels…

a.each_with_index do |b, i|
  b.each_with_index do |c, i|
    e.select { }
    f.each { }
    g.each { }
  end
end

I am a strong advocate of style guides. I also believe logic shouldn’t be nested. This was way too much for my busy brain to process.

The only thing the method was doing is iterating through scraper data, assigning values to objects. Given that I didn’t understand the code I decided to rewrite it. I ended up with 1 class, 2 modules (helpers) which replaced the method with less number of lines of code. It only needed 2 loops but I could have just settled with one.

This was a “99.9% done, quick small fix” according to a client. Surprised at how readable the code was, he asked if I could polish up the other importers as well but it was a busy week so I kept it for later.

Having a chitchat, I asked Peter, a British, about the project. He said that he took a chance with the Myanmarese team following recommendation of an employee. “They had over 30 very nice looking portfolio”. The project had taken 1 year and 2 months. They had quoted him US $ 2500 but later citing changes they had charged him an extra US $ 2500. “Every time they fix 1 issue, they make at least 2 new ones”.

Its sad that people get ripped off by incompetent developers. That is one risk of hiring through the Internet without knowing much about the industry. That is why I recommend users hire through a service like UpWork where you get to see a developers history and ratings and also mediation if necessary.