re: What The For Loop? VIEW POST


This post is good for learning to delve deeper but risks teaching programmers to write code that tries to be too clever. Unless you're writing a library that needs to be highly optimized the original code will be preferable because the intent is much clearer. Favor clear over clever because someone is going to have to maintain that code down the line.



That's the problem with many of these technical interviews, they seem to filter for clever solutions over clean, readable, and reusable code, which take very different skills to write.

This goal of this blog post was to help new developers acquire the skills needed to pass the interview. In real life, I would say the general rule is to optimize for developer time over processor time (depending on the situation of course), which means to write code that's easily readable and maintainable by future developers (including yourself).


While I agree with "favor clear over clever", there's nothing particularly clever about about a for loop that increments its counter variable by two. The C standard defines for loops as for (initial clause ; controlling expression ; post-expression) and i++ is in no way special as a post-expression.


I agree that there's nothing particularly clever about incrementing a counter variable by two in itself. I was just pointing out the risk of going down the clever code path. If I'm maintaining this bit of code that's part of a larger codebase I would want to see something that shows explicit intent like

for(let i=0; i<=20; i++){
  let isOdd = i%2===1

There are other replies to the original post that are clearly going down the clever code path so I think it's worth mentioning.

When is code too clever and when is it overly verbose? Once again, you're preaching to the choir and I agree re optimizing for readability, but in the same vain I find unnecessary assignments like let isOdd = i%2===1 just as distracting. I guess the true moral of the story is that trivial examples are a bad basis for maintainability discussions ;-)

extract isOdd out and you can now reuse it elsewhere. It also improves the readability of the for loop.

const isOdd = n => n % 2 === 1

for (let i=0; i<=20; i++){
  if (isOdd(i) {

isOdd should not need to be a function

Ruby has it as a method. ;-) And I think what Sean meant is exactly that: common functionality like this should be part of the core language, so people don't have to go and implement it themselves every time.

Hence "trivial examples are a bad basis for maintainability discussions". In the provided code there is no "elsewhere" so it really doesn't need to be a function at that time (YAGNI and all that, and Donald Knuth had strong opinions on this one too).

Anyway, in a language with a less poor standard library we wouldn't have to define simple functions to check an integer's parity, so I think this discussion has run its course.

code of conduct - report abuse