Follow @endyourif rss Facebook LinkedIn

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

Published on Sep 13, 2012

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)) {
$cond = array_shift($conditions);



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.


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

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP