Skip to main content
Share Your Experience: Take the 2024 Developer Survey
214 votes

How to write correct loops?

Test No, seriously, test. I've been coding for over 20 years and I still don't trust myself to write a loop correctly the first time. I write and run tests that prove it works before I suspect it ...
candied_orange's user avatar
153 votes

Inside a for-loop, should I move the break condition into the condition field if possible?

Those two examples you gave are not functionally equivalent. In the original, the condition test is done after the "some other code" section, whereas in the modified version, it is done first, at the ...
Pete's user avatar
  • 3,221
123 votes

Is a while loop intrinsically a recursion?

Loops are very much not recursion. In fact, they are the prime example of the opposite mechanism: iteration. The point of recursion is that one element of processing calls another instance of itself. ...
Kilian Foth's user avatar
74 votes

How to write correct loops?

When programming it is useful to think of: pre-conditions post-conditions variants and invariants (of loops or types) and when exploring uncharted territory (such as juggling with indices) it can be ...
Matthieu M.'s user avatar
64 votes

Declaring that a function never returns

This is one of those cases where infinite loops are so predominantly a bad idea that there's no real support/convention around using them. Disclaimer My experience is with C# (as is your code example, ...
Flater's user avatar
  • 51.7k
56 votes

Foreach-loop with break/return vs. while-loop with explicit invariant and post-condition

This is easy. Almost nothing matters more than clarity to the reader. The first variant I found incredibly simple and clear. The second 'improved' version, I had to read several times and make sure ...
Lewis Pringle's user avatar
51 votes

Inside a for-loop, should I move the break condition into the condition field if possible?

I don't buy the argument that "it consumes 3 lines of code" and thus is bad. After all, you could just write it as: if (condition) break; and just consume one line. If the if appears half way ...
David Arno's user avatar
  • 39.3k
49 votes

Inside a for-loop, should I move the break condition into the condition field if possible?

This sort of question has sparked debate almost as long as programming as been going. To throw my hat into the ring, I'd go for the version with the break condition and here's why (for this specific ...
Robbie Dee's user avatar
  • 9,805
45 votes

Declaring that a function never returns

This depends on the type system and the language. Many languages have a type for this, for example never in TypeScript, Nothing in Scala and Kotlin, or Void in Haskell. C has a _Noreturn function ...
Jörg W Mittag's user avatar
42 votes

Is a while loop intrinsically a recursion?

This depends on your point of view. If you look at computability theory, then iteration and recursion are equally expressive. What this means is that you can write a function that computes something, ...
Polygnome's user avatar
  • 2,066
42 votes

Inside a for-loop, should I move the break condition into the condition field if possible?

for loops are for iteration over something1 - they aren't just lol-let's-pull-some-random-stuff-from-the-body-and-put-them-in-the-loop-header - the three expressions have very specific meanings: The ...
Idan Arye's user avatar
  • 12.1k
37 votes

Should <= and >= be avoided when using integers, such as in a For loop?

In curly-braced programming languages with zero-based arrays, it's customary to write for loops like this: for (int i = 0; i < array.Length; i++) { } This traverses all of the elements in the ...
Robert Harvey's user avatar
37 votes

Is a while loop intrinsically a recursion?

Saying that X is intrinsically Y only makes sense if you've got some (formal) system in mind that you are expressing X in. If you define the semantics of while in terms of the lambda calculus, you ...
Komi Golov's user avatar
29 votes
Accepted

What is priming the pump? Sometimes called a priming read

This metaphor almost certainly refers to the practice of establishing the first conditional check in a while loop. If you don't do this, the loop won't work. It is a well-established pattern, and it ...
Robert Harvey's user avatar
28 votes

How to write correct loops?

Use unit testing/TDD If you really need to access sequences through a for loop, you can avoid the mistakes through unit testing, and especially test driven development. Imagine you need to implement ...
Arseni Mourzenko's user avatar
26 votes
Accepted

Is copy and paste the head of for-loop (e.g.:for(let i=0;i<something.length;i++)) violating DRY principle?

The Don't Repeat Yourself (DRY) principle is easy to mindlessly over apply. Keep in mind that the real sin isn't using copy and paste. It's spreading a design decision around in a way that makes it ...
candied_orange's user avatar
23 votes

Clear way to skip the first element in an index based for loop

I hate both. Who said you could use magic numbers? If you're going to start at an offset of 1 how about telling us WHY you're starting at an offset of 1. Adding an equally magic zero explains ...
candied_orange's user avatar
19 votes
Accepted

Foreach-loop with break/return vs. while-loop with explicit invariant and post-condition

I think for simple loops, such as these, the standard first syntax is much clearer. Some people consider multiple returns confusing or a code smell, but for a piece of code this small, I do not ...
Nathanael 's user avatar
17 votes

Should <= and >= be avoided when using integers, such as in a For loop?

It doesn't matter. But for the sake of the argument, let's analyse the two options: a > b vs a >= b. Hang on! Those are not equivalent! OK, then a >= b -1 vs a > b or a > b vs a >= ...
Thanos Tintinidis's user avatar
17 votes
Accepted

Best practice to "continue" from inside a nested loop?

Don't nest: convert to functions instead. And have those functions return true if they perform their action and the subsequent steps can be skipped; false otherwise. That way you completely avoid the ...
David Arno's user avatar
  • 39.3k
16 votes

How to write correct loops?

I agree with other people who say test your code. However, it's also nice to get it right in the first place. I have a tendency to get boundary conditions wrong in many cases, so I've developed ...
Bryce Wagner's user avatar
15 votes
Accepted

Does i in for loops means iteration or index?

It doesn't mean either. It is a variable containing a number that can be used as an index value for an array item. This is evidenced by the fact that i is often used in the context of an array, as in ...
Robert Harvey's user avatar
14 votes
Accepted

Is implementing IEnumerable required to use foreach on collections?

The official documentation looks straightforward to me: The foreach statement repeats a group of embedded statements for each element in an array or an object collection that implements the System....
Arseni Mourzenko's user avatar
14 votes
Accepted

While loop without evaluating data twice

Near "Ideal World" Solution The following is valid C# public static void Main() { var i = 0; string value; while ((value = GetValue(i++)) != null) { DoSomethingWith(value); ...
Theraot's user avatar
  • 9,151
13 votes

Is a while loop intrinsically a recursion?

The difference is the implicit stack and semantic. A while loop that "calls itself at the end" has no stack to crawl back up when it's done. It's last iteration sets what state will be as it ends. ...
candied_orange's user avatar
13 votes

Clear way to skip the first element in an index based for loop

Short answer: the first option is better. The second option just adds noise. It is very unlikely that 0+1 helps the reader to understand that it could have been 0 but it is 1. Much more likely he ...
Florian F's user avatar
  • 1,127
13 votes
Accepted

How to apply SRP in a loop where two things need to be done?

The SRP does not say a function should only do one thing. If that was the case you couldn't write an application or system which does more than one single thing! What you should consider is: Will the ...
JacquesB's user avatar
  • 59.7k
13 votes

Best practice to "continue" from inside a nested loop?

From a more bird view perspective, I would refactor the code so that it looks like this... (in pseudo code, it's too long ago I touched C++) void filterStrings(sl) { /* Filter string list */ ...
dagnelies's user avatar
  • 5,475
12 votes

How to write correct loops?

Off-by-one errors are one of the most common programming mistakes. Even experienced developers get this wrong sometimes. Higher level languages usually have iteration constructs like foreach or map ...
JacquesB's user avatar
  • 59.7k
12 votes

Declaring that a function never returns

I will answer from the point of view of C++, which has not been addressed in other answer at the time of writing. Since C++11, there is an attribute, noreturn, that you can use to signal that a ...
bracco23's user avatar
  • 409

Only top scored, non community-wiki answers of a minimum length are eligible