A Short Rant About Coding Conventions A Short Rant About Coding Conventions

Yesterday's article actually got me a little amped up about coding conventions – Comparing a while loop against a foreach loop of an array – because I never thought I would actually have to do a comparison between a while loop and a foreach loop on an array!  If we go back and revisit the post, I was reviewing a recent CakePHP commit for an optimization on the Hash class.  The code in question is three separate blocks of code that leverage the array_shift function to get the next value in the array with a foreach loop instead.


I truly have no preference in any style, but what I do ask is that you at least pick one style yourself!  Here is the original code in question:

 

The first loop through the $parts array is done as follows:


while (($key = array_shift($parts)) !== null) {
…
}

A little bit further down the file, the $tokens array is looped through like this:


do {
$token = array_shift($tokens);
…
} while (!empty($tokens));

And finally even further down in the file, the $conditions array is looped through as follows:


$ok = true;
while ($ok) {
if (empty($conditions)) {
break;
}
$cond = array_shift($conditions);
…
}

<rant>

Seriously?  I'm a little speechless after just pasting this code into the post…  As a noted in yesterday's post, switching to a foreach loop saw about a 25% speed improvement, but put that aside and just look how inconsistent this code is!

I think a little props should go out to jrbasso for reconciling this code to use a standard format.  I've never committed to an open source project before, but I think if I ever looked that closely at code I would be forced too!

Please folks, I don't care what your standard is, just pick one and stick to it or more important, if a standard is already being used, stick to it as well – or change them all to match.

</rant>

Published on Sep 13, 2012

Tags: CakePHP Tutorial | Theory | foreach | while | PHP

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.