Late last night, I started work on a "list view" class in php, pretty much the same basic concept as an NSTableView in Cocoa/AppKit. The main aim of the class is to make it extremely easy to create a list of tabular data via PHP (mainly for use in control panels).
In my attempt to achieve ultimate simplicity, I designed the
setColumns() method like this:
$listView->setColumns("First Name", 130,
"Last Name", 130,
"Email", 170,
"Phone", 100);I was quite happy, hardly any code at all to specify columns! This is good right?
But after it was all working, I realized how fast this would degrade to chaos if I ever wanted more than two arguments for each column... So I re-worked the whole shebang to work like this:
$listView->addColumn("First Name", 130);
$listView->addColumn("Last Name", 130);
$listView->addColumn("Email", 170);
$listView->addColumn("Phone", 100);Or like this (which is handy if the columns are stored in a DB):
$listView->setColumns(Array("First Name", 130),
Array("Last Name", 130),
Array("Email", 170),
Array("Phone", 100));It was a good half an hour of coding where I basically ripped the guts out of the whole class, and replaced it with something fundamentally different. Not to mention it's quite a bit more code now to specify the columns for the list view, but I went to sleep happy with the fact that I'd written Good Code.
----------
This morning I actually used the class in the real world, and within a few minutes realized a major flaw. I needed it to work with keyed arrays (I refuse to use the A word), which means I need to assign a key to each column! Since not all uses would involve a keyed array, I also wanted the key argument to be optional. Now it looks like this:
$listView->addColumn("First Name", 130, "firstname");
$listView->addColumn("Last Name", 130, "lastname");
$listView->addColumn("Email", 170, "email");
$listView->addColumn("Phone", 100, "phone");It took fully 4 lines of code to implement that in the new class, and it worked flawlessly while still being fully backwards compatible. Wohoo. But what if I had kept the original
setColumns() method? I would have had to make a whole bunch of changes all over the class, and worried about bugs that might have been caused. Not to mention any existing code using the class would have instantly broke.
Motto of the story? Good Code will pay off later.