Going Live with Incomplete Code; Is It Okay?

Even though it isn't required, should code be left incomplete? For example, the last property/value pair in a CSS declaration doesn't need a semi-colon. The code validates and functions normally. So why worry about that last character?

While digging through the Google Maps API, I came across the following code which styles the map widget being embedded on a website:

<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>

The code works as is, but what happens when users add their own styles after the missing semi-colon. A once functioning script breaks.

<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% border:1px solid #999; }
</style>

Semi-colon in PHP

CSS isn't the only place where problems like this can happen. PHP, for example, doesn't require a semi-colon after the last statement in a code block like following:

<?php
$name = 'Jake';
print "<p>You are logged in as $name.</p>" //<-- NOTE: missing semi-colon
?>

As with CSS, the code breaks if more code is added between the missing semi-colon and the closing PHP tag (?>).

<?php
$name = 'Jake';
print "<p>You are logged in as $name.</p>" //<-- NOTE: missing semi-colon
print 'here';
?>

Curly Brackets

So far, we've talked about things which are easily left out by mistake. Maybe Google didn't mean to exclude the final semi-colon in the Maps API code. The curly brackets for if() statements, on the other hand, are intentionally left off by some developers.

<?php
$displayName = true;
$name = 'Scott';
if($displayName)
     print "Name: $name";
?>

However, it won't function as expected when something else needs to happen within the if(), unless the curly brackets are added.

<?php
$displayName = true;
$name = 'Scott';
if($displayName)
     print "Name: $name";
     print 'here';
?>

Even though it requires some extra characters, I always prefer including the brackets. They minimize the risk of errors. Plus the code easier to scan.

<?php
$displayName = true;
$name = 'Scott';
if($displayName) {
     print "Name: $name";
}
?>

Conclusion

Although certain characters aren't technically required to function properly, it may be in your (or your client's) best interest to include them anyway. Especially when leaving them out can lead to errors in future revisions.

If everything functions until something new is added, we're likely to suspect the problem lies in the new code. The old code may not even be considered until other troubleshooting options have been exhausted. To save time and headache, its best to include the unnecessary semi-colons and brackets.

0 Comments

There are currently no comments.

Leave a Comment


Warning: Undefined variable $user_ID in /home/cyberscorp/webdev.cyberscorpion.com/wp-content/themes/scorpbytes/comments.php on line 72