5 ms·
I tend to agree with toxic here. Side effects inside conditionals should be avoided, in short circuit conditionals even more so. In a case like this, my prefer
by DubiousPusher 4y ago
I tend to agree with toxic here. Side effects inside conditionals should be avoided, in short circuit conditionals even more so.
In a case like this, my preference would be to give callback a dummy value and always run it.
I subscribe pretty heavily to the Carmack philosophy of always running the code as similarity as possible and making a decision at the end of a procedure.
- simplotek 4y ago> in short circuit conditionals even more so. I'm curious, what leads you to believe that skipping unnecessary calls to functions with side effects is something to be avoided? Do you believe that unconditionally calling code with side effects specially when you don't have to is something to be desired?
- DubiousPusher 4y agoI believe that running the same code path as much as possible per software cycle is to be desired. The code I'd call in the case that client code didn't specify a function wouldn't produce any side effects. It would be an empty function object/pointer. I would almost always rather support default behavior through dummy data rather than null checks. I find that a lot of software bugs come from the unintended consequences of branching. Especially branches which create state that is consumed later. In fact, I find that most null checks lead to bad software behavior as it often hides bugs. Early outting when null is detected is especially silly to me. The client has just tried to run a procedure which had to be abandoned due to a lack of data and you're just going to quit silently? If you're using dummy data for default scenarios and asserting not null rather than checking, you will eliminate most logical null checks in your code. Though I do concede that in the case where you must support null checks, such a short circuit as above is acceptable and in fact preferable to me over two if statements.
- BeeOnRope 4y agoI think side effect is a red-herring here: it's idiomatic to rely on short circuiting when the RHS relies on the LHS being true to be safe to call at all. In the above example, we check that the pointer is non-null before calling it. The "side effect" we are avoiding is a segfault. In the code that splits the conditional into two, the callback is still run inside a conditional, just by itself.