A situation I encounter pretty frequently is the need to modify the behavior of an algorithm according to some boolean (or more general) “options” parameters.
A plain if-else statement evaluated at runtime can be costly for a critical portion of the code (although in practice, I am not if this is indeed the case) that gets evaluated many times.
My question (more of advice) is which coding approach for the above is preferable in terms of readability, reusability, and performance.
Two approaches that come to mind are:
-
Parametric types – the branching is (presumably) evaluated at compile time since the type parameter is known and multiple dispatch can be utilized. One issue with that is the need to “fully” specify all parameters at invocation, which might be hard to maintain when parameters are removed or added in a future version of the code.
-
Encoding the parameter as a field object of a composite type and then branch according to its values.
Potentially slower, it seems more straightforward to implement.
I hope my situation is clear and not too abstract.
Is there a preferred “Julian” approach?