Get rid of those boolean function parameters (2015)
1–10 of 119 posts
Re: Get rid of those boolean function parameters (2015)
#2I mostly write computation/math-related code and I find using named arguments to be a good practice. This is also quite similar to OP's enum approach, e.g. sth like `calc_formula(a, b, is_gain=True)`.
To be fair, the older I get, the more I like explicit arguments for everything like in Swift (and smalltalk iirc).
Re: Get rid of those boolean function parameters (2015)
#3 v = calc_formula(ia, ib, is_gain=true)
You also have the option of defining a default value for the argument so the old call-sites don't even need modification.Re: Get rid of those boolean function parameters (2015)
#4A workaround in C99 (and more limited in C++20) is to use a single struct which bundles all the function parameters, and then use designated initialization, this also makes function paramaters optional, and at least in C99 they can appear in any order:
my_func((my_struct_t){
.a_bool_flag = true,
.another_bool_flag = false,
.a_string = "Hello World"
});
This is mainly useful for functions which take many parameters. One downside in C99 (but not C++) is that there's no way to define default values for struct items (other than zero/false).Re: Get rid of those boolean function parameters (2015)
#5In python, I love keyword-only arguments for this. Then the caller has to write: v = calc_formula(ia, ib, is_gain=true) You also have the option of defining a default value for the argument so the old call-sites don't even need modification.
Re: Get rid of those boolean function parameters (2015)
#6Another trick, at least in js, is to use destructuring assignment, e.g.
function calc_formula({a, b, is_gain}){
...
}
calc_formula({a:1, b:2, is_gain:true})Re: Get rid of those boolean function parameters (2015)
#7Re: Get rid of those boolean function parameters (2015)
#8This should really be solved by using named parameters or by writing docblocks so that IDE can show hints. Another trick, at least in js, is to use destructuring assignment, e.g. function calc_formula({a, b, is_gain}){ ... } calc_formula({a:1, b:2, is_gain:true})
Re: Get rid of those boolean function parameters (2015)
#9IntelliJ solves this nicely by showing the parameter name at call sites, effectively making it look like the language has named parameters.
Re: Get rid of those boolean function parameters (2015)
#10In a much simpler case of arcs in SVG, I still need to check flags to do the correct path (https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Pa...).