Sunday, August 10, 2008

When to reinvent the wheel

One of the cardinal rules of software development is to never reinvent the wheel. I have in my ten years of software development strictly adhered to this rule, primarily because programmers are lazy. For the most part it is in your best interest to used tested code the is already written, however sometimes it can be a detriment.

Recently I was working on a project where I wanted to do an auto suggest drop down for a text box. I started off, as usual, slogging through the net looking for something that work. Without too much work I was able to find about three contenders. I downloaded, installed and tested each. None of the three was really what I wanted so I adventured back to the Internet in search of the perfect auto suggest JavaScript and before I knew it I had spent a whole work day (8 hours) just scouring the internet.

I took a step back and wrote:

function suggest() {
var searchBox = document.getElementById('search-form-query');
var suggestions = document.getElementById('suggestions');

var url = 'searchData.cfm';
var pars = 'field=' + searchBox.value;

var ajax = new Ajax.Updater(
{success: 'suggestions'},
url,
{method: 'get', parameters: pars, onFailure: reportError});

suggestions.style.display = 'inline'
}

function hideSuggestions() {
var suggestions = document.getElementById('suggestions');
suggestions.style.display = 'none'
}

With a tiny bit of HTML to help:

<div id="suggestions" style="overflow: auto; position: absolute; background-color: white; width: 150px; height: 250px; display: none;" onclick="hideSuggestions()">This is where the auto suggestions will go</div>

This code took me maybe ten minutes to write and test and it was exactly what I wanted in the end. In the end it was far more efficient for me just to write the code and move on. It's important for programmers to strike a good balance between writing their own stuff and using packages from the Internet.

No comments: