Monday, May 15, 2006

be explicit

Another tip for better coding:
Always be explicit in your code.

Why? Well, consider this example. I was working on an application that required that the order of the rows in a grid that had been sorted and grouped be in sync with the order of the same results in an arraylist.

The current version of the code reacted to events from the grid to re-sort the Arraylist. Good. Except that when the grid was grouped, the arraylist wasn't being sorted correctly. :P

Two options (of several more...)
1. Find all of the events and ensure that the arraylist is synchronized each time the event fires.
2. Define points where I need the arraylist to be in sync with the grid and sync then.

I chose #2. Why?:
I know when I need the arraylist to be in sync and so I force it to be. Therefore I am being explicit about what state I need the data to be in. Relying on the events to sort the ArrayList is implicit. This means that I can never be sure that the order is correct unless I check it is. That's just a bomb waiting to go off.

Synchronizing in my function is similar to a precondition. This is a step in the right direction. My code required that the list was in order and I made it so. Therefore I ensured that the precondition was met in the function that needed it to be.

Sample Code:

private void OpenSelectedItem()


Now for simplicity's sake, I've ignored the implicit coupling (I'll post on this later). And yes, those are the names of my functions. If you don't like em, tell me why. I'd love to discuss coding styles/techniques with you.

No comments: