Bad Code 101: Don’t compute inside arrays

Abdullah Momoh
2 min readSep 18, 2019

There are so many bad coding habits and most times we do not realize how much of it creeps into our code daily. If we are saying our truths, then I'm not going to lie, “I write bad code sometimes and so do you”. This isn’t news to most developers and if you decide to say you do not, then the entire universe of programmers hail you.

Bad code isn’t necessarily your fault and it's not mine either — I didn't help you write it. That's why its easy advice to say “if you don't want to write bad code, then don’t code at all”. Yes, you heard me, don’t write a single line of code. Hopefully, you can live through a day of not coding, Although I have survived months before, I'm sure that's something I don’t want to live through again.

But what causes bad code? There numerous reasons why we sometimes write bad code which centers around poor design, poor coding practices and taking shortcuts. Yes, we all love our shortcuts, don't we?

Why are these two different?

Taking a look at the two snippets of code above to remove duplicate items in an array, we can observe that although but basic inspection they seem like they should do the same thing, they produce different outputs. This really amazed me when I first saw it.

The distinction is clear, in line 7 the correct array values are being accessed and changed but the value of variable j isn’t changing, which in return allow you to always see one as your output. While the second code explicitly states the increment of variable j.

The moral of this story is to be clear about what code you are writing. Avoid using shortcuts unless it is particularly built into the language. Make your code readable by humans and executable by computers and not the other way around. This makes it easier to avoid logical errors like the one you see above. make code explicit and simple.

In the words of Tony Stark, “Don’t do anything I wouldn’t do, and don’t do anything I would do”. Just stay in the grey area.

Leave a comment and tell me what you think, is this something you have faced too? Also, if you have other instances of this let me know. : )

--

--