Saturday, July 9, 2011

Simple trick to make your code more readable

Recently I read the following post by Martin Fowler: http://martinfowler.com/bliki/FlagArgument.html that advocates for making boolean parameters more readable. He gives some great advises, but some times they involve too much code refactoring or produce lots of methods that are basically the same.

What I find very useful is to pass the parameters by name where the meaning of the bool constant is not clear. To illustrate what I mean, I will use an example from his article:

Instead of:
reserveSeat(aCustomer, true);

I would rather use:
reserveSeat(aCustomer, isPremium: true);

This make much clearer what is the meaning of the bool parameter, while reading the code. This way, I try to apply the principle "write read-friendly code instead of write-friendly code" :)