Is there some rule when to use two functions or when to pass boolean parameter.
Thanks
Boolean Parameter is a case of Control Couple, where a method parameter is defaulted to true or false. A Boolean Parameter effectively permits a method's caller to decide which execution path to take.
We can use bool-type variables or values true and false in mathematical expressions also. For instance, int x = false + true + 6; 3. is valid and the expression on the right will evaluate to 7 as false has a value of 0 and true will have a value of 1.
The ProcessList method takes a Boolean flag to determine which control flow it should execute to provide the right result based on the function call. Using a Boolean parameter to determine function behavior is a code smell that every programmer must avoid.
Once you've created the build job, Jenkins will display the item's configuration page. On this configuration page, there is an unselected checkbox next to text that states: "This project is parameterized." Select this option, and in the drop-down that subsequently appears, choose the option to add a Boolean parameter.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With