Code looks bad enough when you have to constantly indent. It has always pained me to indent a large chunk of code (regardless of the language) just to be the body of some branching statement.
For example, if you have a looped chunk of code like:
// For some amount of times to loop // Do something cool // Do more that's cool // Do the coolest thing ever // ...5 more lines of coolness...
And you only want to execute that loop body under some condition:
// If you're cool then...
The code becomes slightly less readable to indent only for that condition, as such:
// For some amount of times to loop // If you're cool then... // Do something cool // Do more that's cool // Do the coolest thing ever // ...5 more lines of coolness...
In my relatively short mobile development experience, you begin to throw in more conditions just to make sure that an object exists before trying to use it. Make the mistake of assuming an object was created or that a function returned the proper value and you’re in for an ugly Application Not Responding (ANR) dialog.
The solution popped into my head! Instead of making your code ugly for just a single condition, why not use the
For clarification, the
return; statement is usually used to abruptly exit a
void function. The
continue; is used to skip an iteration of a loop.
I’ll be honest, I’ve never had a use for those statements. I’ve even see textbooks say that you shouldn’t really use them because you can always rewrite your code to omit the use of those keywords. That’s definitely true for beginner programmers, where you don’t want them to write loops and branches always using the aforementioned statements. However, it hurts my heart to indent a large chunk of code. Of course, you could say “move that code to a function and then you’d only have to indent the function call,” but I like to see the important parts of my code on a single screen!
In any case, using the continue statement described above, the final code becomes:
// For some amount of times to loop // If you're NOT cool then CONTINUE // Do something cool // Do more that's cool // Do the coolest thing ever // ...5 more lines of coolness...
This means that if you don’t meet the coolness condition to execute the loop body, then just skip that iteration!
To me, that code looks cleaner and easier to read. Of course, this is a small example; just imagine a much larger body of code. Readability is one of the most important factors for your code, or so I’ve been told.
I’m a neat-freak, but only in code!