Thursday, August 13, 2009

Blindingly Obvious Programming Tips #3

I've not implemented this tip myself yet, since I've only just had the idea, but I thought I'd commit it to screen before it disappears from my head.

One of my peeves about programming are function calls with long lists of esoteric parameters. Stuff like "sprite.draw(10, 12, true, true, false, true);". Unless you can memorised the order and meaning of each of the parameters, you have no idea what that function call is going to do exactly. Multiply that by the number of functions in a typical program, and you realise that a solution is needed.

Some languages can get round this and have named parameters. I don't believe Java has those yet; the closest we have is javadoc annotations. However, my solution is pretty simple: create "constants" (or as close as Java will allow) with meaningful names that are simple booleans. Then the above function call can be re-written as

sprite.draw(10, 12, B_COLLIDES, B_FOREGROUND, B_HAS_HALO, B_FLICKER_SLIGHTLY);

Much more understandable.

1 comment:

Vagabond said...

This is certainly more readable.
The question is that whether this is your function or it is in some framework? Because if this is your code then using parameter objects is probably a better idea. (Parameter objects are wrapper classes containing all the calling parameters as fields / maps with name:value pairs for parameters). Setting them up is usually quite easy, and they help future refactoring if more parameters are needed.
If the setter functions return the object itself, then the following syntax can be used:
DrawParams.
setWidth(30).
setHeight(40).
setType(DrawParams.AsyncRefresh) ...