One man's voice Thoughts, rants and commentary of a simple man

12Mar/094

Coding clean should be a lifestyle

Dear rookie PHP coders/script kiddies/n00Bs: if you plan to use a variable or array index please remember to initialize them first or I will hunt you down and gut you like a pig. Kthnxbai.

I am in the middle of a redevelopment project right now that is pissing me off beyond imagination. The main reason is because the original developer of the codebase decided that initializing variables, checking existence of variables and checking existence of common array indexes was not necessary. And it got me thinking... coding clean should not just be a high priority, it should be a way of life for developers.

For those of you that may just be getting started in the big scary world of PHP development I want to offer a suggestion: before you even think of using a variable or array index either initialize it or check its existence.

What is initializing a variable or array index you ask? Simple. Declare it with a value. Like this:

<?php
// Initialize a variable
$myVar = null;
 
// Initialize a variable as an array
$myArray = array();
 
// Initialize an index
$myArray['myIndex'] = null;
?>

That isn't that hard, is it? Now lets that this a step further and make sure that before we use something it is actually available to us, shall we?

<?php
if (isset($myVar)) {
  // Do something based on $myVar being set
}
 
if (empty($myArray)) {
  // Do something based on $myArray being either not 
  // set or set to a value equal to (boolean) false
}
?>

Using empty() and isset() are two things you can do before using a variable. This allows you to not only check if a variable has been set but also allows you to check a specific empty value.

Something to take note of here is that isset() will still return false if you check a variable that has be assigned a value of 'null'. However, because it has been declared you can use the variable in conditionals and other expressions without worry of generating an undefined variable notice.

<?php
$myVar = null;
 
if (!$myVar) {
  // So something if $myVar evaluates to (boolean) false
  // And you don't have to worry about throwing errors now
}
?>

If you plan on using a constant, which is not a variable, then you would use defined().

<?php
define('ROBERTROCKS', true);
 
if (defined('ROBERTROCKS') && ROBERTROCKS) {
  echo 'Man, Robert must rock';
}
?>

Moving into an area that is a tad more useful, there are times when your code is going to enter a loop or other construct (like a switch for example) and something done inside of that construct will set a variable that you will use after the construct closes. When this happens, make sure to initialize your var outside the construct so that if the construct never opens or is never entered you can still use the variable after the construct closes.

<?php
/**
 * Make sure we have clean access to the variable 
 * regardless of whether the construct is used
 */
$myVar = '';
 
while (loopRuns()) {
  $myVar .= getLoopVal();
}
 
/** 
 * Since we made this variable before entering
 * the construct we can be sure we can use it 
 * without issue even if the loop never happens.
 */
echo $myVar;
?>

So to close this out let me point out a few things that you should never see in your code. Ever.

<?php
/**
 * This is crap. Don't ever do this. If a request is made
 * to this page without a querystring then $_GET['id']
 * will not be set and you will look like an ass for not
 * knowing how to code cleanly.
 */
$id = $_GET['id'];
 
/**
 * This is another stupid. How do you know if the session
 * variable has been set? You don't, and if it isn't set you
 * will be notified.
 */
if ($_SESSION['hasVar']) $hasSessionVar = $_SESSION['hasVar'];
 
/**
 * Last example of what not to do... never build a var
 * inside a construct for use outside the construct without
 * initializing it.
 */
switch ($myVar) {
  case 'crap':
    $newVar = 'This is crap';
    break;
 
  case 'bull':
    $newVar = 'This is bull';
    break;
}
 
echo $newVar;
?>

I hope this helps someone learn to code a little cleaner. And perhaps save you all sorts of curses and negativity by developers that might have to try to work on your code long after you stopped working on it.

Comments (4) Trackbacks (0)
  1. Preach the Word my brother. :-)

  2. Hallelujah and Amen!

    Truly I wish all developers followed your elegant style of coding Paul. There is much to be learned from the way you program.

  3. You’re the only one that ever made me feel good for doing that. You saw some of my c++ code for a minesweeper program and called it pretty. On a side note. One benefit to coding is you get comments like this:
    “At the age of 17 I’ve been programming for about 3 or 4 years now..

    And I look at some of your guys’ stuff

    And I feel like I’m in the presence of GOD”

    And if your ego is like mine that also makes it worth it.

    Lesson being: code clean so you feel special. That is all. :-D

  4. If there is one thing I truly appreciate in the world of programming it is clean coding. And I will be the first to applaud you if you code cleanly.

    Personally I love to be able to review code and be able to parse it in my head as I read it. When you can do that then the code makes sense and becomes more poetic, more elegant, than a bunch of commands entered into a text file. It becomes something altogether more beautiful.


Leave a comment

(required)

No trackbacks yet.