Programming Nuances, PHP and JavaScript

Two little snippets, some simple things that seem to be forgotten when writing code.  First, a general example using PHP; have you ever found yourself writing a loop that looks something like this?

$i = 0;
while ($row = mysql_fetch_assoc($result) {
	// ...
	// maybe something about $i % 2 to determine even-from-odd rows
	++$i;
}

If so, remember this: you are (effectively) building a complicated, difficult to read and easy-to-break for-loop. There is no magic law that says that all three arguments of a for-loop must be related to the same variable (heck, you may have even used a few of them with no arguments in one or more positions). Consider the following:

for ($i = 1; $row = mysql_fetch_assoc($result); ++$i) {
	// ...
	// the same code can go here
}

While the differences may seem semantic-bordering-on-syntactic-sugar at first (there is no real execution difference between for-loops and while-loops, of course), consider what differences they offer to you as a developer:

  1. When looking at the for loop, you know immediately what is involved, instead of hunting for the declaration and incrementation of $i, or whatever your preferred increment-variable flavor is.
  2. It saves code real-estate
  3. You can easily edit the contents of the loop, as well as what contains the loop, and not worry about destroying an important variable declaration, iteration, etc.

Of course, this isn’t a serious gripe, just a nudge towards thinking outside of “traditional” declarations and using something that will be easily maintainable.

Second, remember that everything in JavaScript can be treated like an object-reference.  Of course, you’ve probably been told this before, but I want to bring up one instance in particular: functions.  If something returns a function reference, you can execute it directly, without cluttering the parser/code with unnecessary calls to things like setTimeout(). Consider the following code I have been running into a lot recently (using Prototype 1.6):

setTimeout(someFunction.bind(window),10);

While this will certainly do what you want, the call to setTimeout() is superfluous, and serves only to confound the matter. Since it is an object reference, you may use function notation to execute it like any other function object, such as:

someFunction.bind(window)();

Not only is it more concise, but when you look at it you know exactly what you’re doing with it.

Remember, while avoiding cleverness for cleverness’ sake, it is important to use your brain while programming. Strive for elegance and keep on truckin’.

Recent Entries

Comments are closed.