Tuesday, June 20, 2006

Avoid Boolean

It is possible to misuse a boolean parameter to do something stupid. For example, if you want a function which converts your data into a string representation and another which converts it into integer, you could do something like this:

object Convert(bool stringornot)
{
if (stringornot)
{
// return as string
}
else
{
// return as integer
}
}
Oh my god that's totally unreadable. Oh my god my god my god. With this single example, I am now going to make a straightforward suggestion. Do something better. Have two functions for the alternative cases. E.g.:

string ConvertToString()
{
// return as string
}

integer ConvertToInteger()
{
// return as integer
}
Now, the masterstroke. Using the extrapolation design pattern, I will now propose that no function should ever take a boolean argument to express anything which might affect its logic. This ringfencing will cause you to jump through hoops. I would also suggest you try to avoid passing more than one parameter to any function and would also suggest that each function have a maximum of one line of code in it.

0 Comments:

Post a Comment

<< Home