Hot answers tagged

210

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 works. Test each side of every boundary condition. For example a rightIndex of 0 should do what? How about -1? Keep it simple If others can't see what it does at a ...


180

Pushing works well for 1, or a limited number of users. Now change the scenario with one photographer and 1000 users that all want a copy of the picture. The photographer will have to walk to 1000 piles. Some of them might be in locked office, or spread all over the floor. Or their user on vacation, and not interested in new pictures at the moment. The ...


168

Yes and no. Ultimately, there's nothing recursion can compute that looping can't, but looping takes a lot more plumbing. Therefore, the one thing recursion can do that loops can't is make some tasks super easy. Take walking a tree. Walking a tree with recursion is stupid-easy. It's the most natural thing in the world. Walking a tree with loops is a lot less ...


153

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 start of the loop body. Code should never be rewritten with the sole purpose of reducing number of lines. Obviously it's a nice bonus when it works out that ...


121

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. The loop control machinery merely jumps back to the point where it started. Jumping around in code and calling another block of code are different operations. ...


106

I'm really surprised that only one person has mentioned WebSockets. Support is implemented in basically every major browser. In fact PubNub uses them. For your application the browser would probably subscribe to a socket that would broadcast whenever a new photo is available. The socket wouldn't send the photo, mind you, but just a link so the browser ...


91

This is a common conceptual difficulty when learning to use NumPy effectively. Normally, data processing in Python is best expressed in terms of iterators, to keep memory usage low, to maximize opportunities for parallelism with the I/O system, and to provide for reuse and combination of parts of algorithms. But NumPy turns all that inside out: the best ...


74

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 very, very, useful to not just think about those but actually make them explicit in the code with assertions. Let's take your original code: /** * Inserts ...


65

I would regard this as an appropriate place to use command/query separation. For example: // query var validItems = items.Where(i => i.Field != null && i.State != ItemStates.Deleted); // command foreach (var item in validItems) { // do stuff } This also allows you to give a good self-documenting name to the query result. It also helps you ...


63

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, seems to be), but I would think that this is language-agnostic, unless there are languages which automatically wrap method calls in separate threads. Based on ...


62

Nested loops are fine as long as they describe the correct algorithm. Nested loops have performance considerations (see @Travis-Pesetto's answer), but sometimes it's exactly the correct algorithm, e.g. when you need to access every value in a matrix. Labeling loops in Java allows to prematurely break out of several nested loops when other ways to do this ...


60

We write loops like: for(x = 0; x < 10; x++) The language could have been defined so that loops looked like: for(x = 0, x < 10, x++) However, think of the same loop implemented using a while loop: x = 0; while(x < 10) { x++; } Notice that the x=0 and x++ are statements, ended by semicolons. They aren't expressions like you would ...


56

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 all the edge conditions were right. There is ZERO DOUBT which is better coding style (the first is much better). Now - what is CLEAR to people may vary from ...


51

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 through the loop, it of course has to exist as a separate test. However, if this test appears at the end of the block, you have created a loop that has a continue ...


49

To a degree, I stopped taking this quote seriously at "Tabs are 8 characters". The whole point of tabulators is that they are not a fixed number of characters (if anything, a tab is one character). What a load of tosh. Similarly, I'm not completely convinced that setting a hard-and-fast rule of "three levels of indentation" is sane (as much as setting a hard-...


49

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 case): The for loop is just there to specify the iterating values in the loop. Coding the breaking condition within that just muddies the logic IMO. Having a ...


44

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 specifier keyword. In languages that support annotations (e.g. Java, C#), you could create a custom annotation that communicates your intent. Some IDE vendors or ...


43

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 first one is for initializing the iterator. It can be an index, a pointer, an iteration object or whatever - as long as it is used for iteration. The second is ...


42

Sometimes good enough is good enough. Of all the possible ways to implement a "real-time" communications process, polling is perhaps the simplest way. Polling can be used effectively when the polling interval is relatively long (i.e. seconds, minutes or hours rather than instantaneous), and the clock cycles consumed by checking the connection or resource ...


39

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, and it doesn't matter whether you do it recursively or iteratively, you will be able to choose both approaches. There is nothing you can compute recursively ...


37

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 array, and is by far the most common case. It avoids the use of <= or >=. The only time this would ever have to change is when you need to skip the first or ...


37

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 might mention recursion*; if you define it in terms of a register machine, you probably won't. In either case, people probably won't understand you if you call a ...


36

Actually you should break the function down first: A loop has a few parts: the header, and processing before the loop. May declare some new variables the condition, when to stop the loop. the actual loop body. It changes some of the header's variables and/or the parameters passed in. the tail; what happens after the loop and return result. Or to write it ...


33

It's not an anti-pattern, because that would mean it is a commonly used technique that's problematic somehow. This code fails to meet the "commonly used" criterion. However, it is problematic. Here are some of its problems: Misleading: it uses a loop structure, but never executes more than once. Hiding a check: the != null check is easy to miss where it is ...


31

The HTTP protocol is limited in that the client MUST be the one to initiate the request. The server cannot communicate with the client unless responding to a client's request. So to adjust your real world example, add the following restraint: User 2 can ONLY respond to User 1's questions with a single sentence reply, after which User 1 must leave. User 2 ...


31

Are there any cases where a task can only be done using recursion, rather than a loop? You can always turn recursive algorithm into a loop, which uses a Last-In-First-Out data structure (AKA stack) to store temporary state, because recursive call is exactly that, storing current state in a stack, proceeding with the algorithm, then later restoring the ...


29

What you are doing is obfuscating your code, not making it clearer. It takes a lot of effort to understand that this “loop” will only execute once. Instead, you could just use a statement block to restrict the variable's scope: { JButton b = new JButton("+1"); b.setForeground(Color.WHITE); ... } If you're into lambdas, you could also define a ...


29

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 a method which takes the values which are superior to zero, in reverse order. What test cases could you think of? A sequence contains one value which is ...


26

Nested loops are frequently (but not always) bad practice, because they're frequently (but not always) overkill for what you're trying to do. In many cases, there's a much faster and less wasteful way to accomplish the goal you're trying to achieve. For example, if you have 100 items in list A, and 100 items in list B, and you know that for each item in ...


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