I have a question of "good design practices" in C++. I am writing a numerical library in C++11 and I use at lot of metaprogramming and template-based technique. But I have a very basic question :
Consider a function that can have a two very close behaviours excepted an option that can be activated by a boolean flag. I consider only a flag that can be set/unset by the developer and not a flag that can be set/unset at runtime. There are 3 possibilities of design :
1) Write two functions with the explicit option in their name :
myFunctionFlag1(...);
myFunctionFlag2(...);
2) Use a template parameter :
template<bool Flag> myFunction(...);
3) Use a variable parameter :
myFunction(..., const bool flag);
In terms of good design practices which solution is acceptable/unacceptable ? If there is a best solution, which one is it and why ? If there is a worst solution, which one is it and why ?
EDIT : for the considered functions the runtime overhead could be considered as negligible, so this is not the most critical point.
EDIT 2 : I know that all the three work. But as my library will have users, it needs to have a reliable/good design.
Is the option 2 common (because it seems to me to be a good compromise) ?
To use boolean, a header file stdbool.h must be included to use bool in C. bool is an alias to _Bool to avoid breaking existing C code which might be using bool as an identifier. You can learn about _Bool here in detail.
In C the terminology of boolean is associated with data type and Boolean is termed as one of the data types in the C Standard Library and can be invoked after including the stdbool.h header file We can create a custom type bool by leveraging the power of keyword typedef and enumeration (enum) in C.
Basically, the bool type value represents two types of behavior, either true or false. Here, '0' represents false value, while '1' represents true value. In C Boolean, '0' is stored as 0, and another integer is stored as 1.
In the above syntax, bool is the data type of the variable, and variable_name is the name of the variable. Let's understand through an example. In the above code, we have used <stdbool.h> header file so that we can use the bool type variable in our program.
None of the above. Boolean flags are terrible for code readability. If the flag-controlled functionality is sufficiently small that it makes sense to use a single function, then use a single function, but don't use bool
as the type of the flag. Instead, use an enumeration with enumerators that have useful names:
enum class MyFunctionMode { EnableFoo, DisableFoo };
void myFunction(..., MyFunctionMode mode);
This pattern makes it easy to understand at the call site what options are being provided to the function. Multiple options may be combined using flags.
My recommendation would be to use the option 1.
Comments:
My 2 cents.
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