Hi,
Is there some rule when to use two functions or when to pass boolean parameter.
Thanks
Hi,
Is there some rule when to use two functions or when to pass boolean parameter.
Thanks
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.
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")