Mastery of Programming-Fu
- 0
- Add a Comment
I recently came across a post on Gianni Milanesi’s blog regarding Javascript-Fu, it’s a mixture of good points and pseudo-tales. The heart of the matter is that if you follow some simple guidelines when you write code (JS or any type), you can make life much easier for yourself and others.
I’ll give you an example of what can happen without some *-Fu: here’s some PHP code I wrote in January of 2005. It’s purpose is to keep a timing log of events, simply call DebugLog(”Some action occured”) and it’ll add your event to the list, plus the time since the last event, and the total time up to that point. There are other functions to handle output of the log, but this is the meat of it:
function DebugLog($t = "Unknown Marker Point") /* $t = Marker Text */
{
global $dg, $DEBUG_MODE, $DEBUG_PFX; /* $dg['p'] = Log Iteration */
if (!$DEBUG_MODE) return; /* Clause to exit early */
list($a, $b) = explode(" ", (($n = microtime()) ? $n : "0 0")); /* $n = Now */
list($c, $d) = explode(" ", (($l = $dg['l'][(isset($dg['p']) ? $dg['p']++ : ($dg['p'] = 0))]) ? $l : $n)); /* $l = Last Time */
list($e, $f) = explode(" ", (($s = $dg['l'][0]) ? $s : $n)); /* $s = First Time */
$dg['o'][(($dg['l'][$dg['p']] = $n) ? $n : 0)] = (!empty($DEBUG_PFX) ? "{$DEBUG_PFX}: " : "") . ($t != FALSE ? ("{$t} (<b>" . (($q = sprintf("%0.
4f",($b-$d+$a-$c))) ? $q : 0). "s</b> / " . ((($r = sprintf("%0.4f",($b-$f+$a-$e))) ? $r : 0) != $q ? "{$r}s" : "Init") . ")") : "");
}
… yuck, so compressed I have trouble breaking it down to it’s component parts - and I wrote it. It’s handy to show off for a ‘l00k at my skillz’ angle (if you love ternary conditional operators), but from a maintenance standpoint it’s nasty. Imagine if you wrote 1,000 lines of code for a client in this way, then got “hit by a bus” (as my boss terms it), where would your successor begin?
So, heres what you can do:
- Follow a simple set of coding guidelines. When I began writing Drupal modules, I noticed both the core and third-party code followed particular standards. I still follow them now.
- Comment, comment, comment. It doesn’t slow parsers down, they ignore them. Your intentions in code are not always clear, by adding a few words it becomes much more obvious to others, and to yourself; if you leave and return to it months later.
- Optimize your code, but not to the point of obfuscation. Again, parsers don’t really care if you name your variable $a or $inventoryContents.
- Encourage peer review of your code when possible, theres always the chance that they’ll see a better way to do something, or learn a new method in the process (and vice versa). In these modern times web scripting languages can change significantly in a short time span, keeping up to date through RTFM’ing and talking to fellow coders is a good combo.
May your code be good and your returns high. :)
[tags]programming,code,guidelines,fu[/tags]
