spacer
Yehuda Shiran March 25, 2001
Defensive Programming
Tips: March 2001

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
Google Going Native With Chrome
Mozilla Fixes Firefox Flaws as 3.5 Release Nears
Microsoft and Novell Still Bosom Buddies

Defensive programming is a technique you can use to improve the robustness of your programming. You need to think about possible errors from your users. Don't assume anything. The only sure thing is that if something can go wrong, it will. It's similar to taking a defensive driving course. One way to prevent accidents is to think ahead and be aware of potential problems. It's the same in programming. You could write the most brilliant algorithm, but your users may not know how to use it, or, even worse, use it incorrectly. Let's look at an example. The following code includes a mistake. Can you find it?

function Employee(a) {
  this.name = a;
}

function init(){
  John = Employee("Johnson");
  alert(John.name);
}

You guessed it right. The code is missing the keyword new before the constructor name. Calling init() will give an error. One defensive programming action would be to add a check inside the constructor. It will match the calling object with the constructor class, and will call the constructor (with new this time), to create the object:

function Employee(a) {
  if (!(this instanceof Employee)) return new Employee(a);
  this.name = a;
}

function init(){
  John = Employee("Johnson");
  alert(John.name);
}

Try calling init(). You will never get an error, because we create the object for you, even if the calling code doesn't.


People who read this tip also read these tips:

Look for similar tips by subject:

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
XML and PHP Simplified · Creating a ASP.NET Contact Form · Data Filtering with PHP
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Intel to Host Live Nehalem Q&A · 12 Tips to Troubleshoot Network File-Sharing · 10 Tips for Selling on Kijiji