4 ms·
Writing functions that return side effects as a message instead of running them within the function must be one of the most underrated things.
by oxff 4y ago
Writing functions that return side effects as a message instead of running them within the function must be one of the most underrated things.
- biorach 4y agoCan you elaborate? This in the context of a message-passing architecture? Or do you mean as callbacks?
- sidcool 4y agoCan you give an example?
- phtrivier 4y agoIf your function is supposed to perform some side effects, and you want to test complex cases where the effects are difficult to verify, than changing the function from function foo() : void { doBar(); if (...) { doBaz(12); } } to something like: function fooEffects(): Effects[] { results = [ { type: 'bar' }] if (....) { results.push({ type: 'baz', value: 12 }) } return result } function executeEffects(effects: Effects) { if (effects.type === 'bar') { .... } if (effects.type === 'baz') { ... } } Then you can easily test the "fooEffects" function (it just return values that you can compare to the expected effects"). The `executeEffects` is still hard to test (you must mock / fake / stub things), but at least you only have to setup the mocking once. Obviously, all hells break loose if you need to test some effects that depend on the result of other effects, which limits the technique to "single flow" of effects (printing stuff, sending commands, etc...)
- substation13 4y agoThis is often called defunctionalisation