views:

73

answers:

2

Hi,

Is there some rule when to use two functions or when to pass boolean parameter.

Thanks

+7  A: 

It has been a while since I last re-read Code Complete, but I vaguely recall McConnell addressing this, and the words "disjunctive conherence" pop into my head. Briefly,

void f(int x, int y, bool b)

versus

void f1(int x, int y)
void f2(int x, int y)

is often a choice, and depending on how similar or different f would behave under true versus false, it may make sense to break it into two functions and give them distinct names. Often a third choice is better, which is to change the bool to a two-value enum, where the enum name makes the distinction clear.

The key is to look at the call-sites, and see if the meaning is clear just from reading the code. If you are tempted to put a comment on every boolean call-site:

f(3, 4, true /* absoluteWidgetMode */ )

and the call-sites usually call with boolean constants, that's a strong smell that you should break it up into multiple functions.

Brian
+4  A: 

Boolean parameters are meaningless most of the times, basically deserving the same criticism magic numbers do. You have no chance of unterstanding what is done by just looking at the function call.

So even if it's convenient to have a boolean parameter for very similar codes (appending/overwriting a file), keep it internal, private and don't let this be visible in the interface.

Instead, always force the programmer to be explicit:

Use enumerations to give meaningful descriptions for the distinction or just use separate functions.

Compare:

WriteFile(path, "Hello, World", true)

with

WriteFile(path, "Hello, World", FileMode.Append)

or simply

AppendFile(path, "Hello, World")
Dario
Note that this does not apply to languages with named parameters. `WriteFile(Append: True)` is probably as readable as `WriteFile(Mode: FileMode.Append)`.
sepp2k
@sepp2k: True, though I don't like the named parameter approach - despite being verbose - because their use isn't enforced and thus meaningless parameters are still likely to occur (e.g. due to laziness). Making argument names compulsive would improve the situation, but probably reduce possibilities for abstraction (higher-order functions, delegates, partial application, tacit programming). In this cases too, strong types or different functions are still the best choice.
Dario