I'm trying to make this as generic as possible. Let's suppose that in an if-statement, I am checking for whether some boolean expression A is true. Let's say that there are specific cases to A being true, A.a, and A.b, which are mutually exclusive. The same is true for another boolean expression B. Then, consider the following code:
if (A) {
if (A.a) {
somethingSpecificToAa();
foo();
}
else if (B) {
if (B.a) {
somethingSpecificToBa();
foo();
}
} else {
foo();
}
In my actual code foo()
is not a single function but multiple, long lines of code. Repeating them this many times seems smelly to me, so I assume some refactoring is in order.
Since foo()
is executed when:
- A.a is true
- B.a is true
- Neither A nor B are true
I thought of the following:
if (A.a) {
somethingSpecificToAa();
} else if (B.a) {
somethingSpecificToBa();
}
if (A.a || B.a || !(A || B)) {
foo();
}
which should have the same behaviour. Is this the best way to go about it? Note that the condition in the 2nd if statement of the 2nd example ends up being extremely long in reality, which is why my code still looks like the 1st example (I hate breaking up a single if
over several lines.) I have also thought about making a lambda that returns a bool
that is equivalent to A.a || B.a || !(A || B)
and plugging the lambda into the 2nd if statement instead. Alternatively, I could retain the structure of the 1st example, but replace the many lines of each foo()
with a (void
) lambda that does the same, although I'm not sure this resolves the smell.
Am I over-engineering at this point, thinking about lambdas? Which approach is best to maintain clean code?
Aucun commentaire:
Enregistrer un commentaire