Wednesday, February 20, 2008

Refactoring to Make Code More Human Readable, a Little Example

I code a little tool in .Net today and need to initiate something different based on whether the second argument is given or not. The program would go something like (to protect the innocent, I'll use very generic name here) :

myProgram arg0

or

myProgram arg0 arg 1

First, doing the simplest things first, the arguments handling goes something like

   1:
2:if (args.Length > 1)
3:{
4: //initiate something the standard way
5:}
6:else
7:{
8: //initiate diffrently
9:}
10:


Its works ok but the conditional above left something to be desire, so I refactor it by extracting checking argument length into function :

   1:
2:if(!supportFileIsGiven(ref args))
3:{
4:
//initiate something the standard way
5:}
6:else
7:{
8: //initiate things differently
9:}
10:


Suddenly the code become a more readable english. It tells more story and deliver meaning. Given a choice, I'll choose code with the style of the second one to work on anytime of day.

1 comment:

tlcarrut said...

Yes, more readable.

But even better -- some comments somewhere which describe what arguments will be acceptable by the program.

Sometimes a "usage" function is good enough. Sometimes even more details is needed depending on the complexity of the program and the interaction among the arguments.

Your example is good for a start but it is just the tip of the iceberg. Don't be afraid to include comments in your code. I know it is not "cool" but it makes the program more maintainable.