Re:Push ifs up and fors down
by layer8 on Wednesday November 15, 2023 @06:00PM
(#38283769)
One variation on this theme is to use subclass or function polymorphism. This lets you decouple (in time) (a) the code that decides what to do based on the condition from (b) the code that actually does what was decided. In TFA’s enum example, instead of the enum values you could pass the foo/bar functions around as values (or instances of different subclasses implementing a common interface method as either foo or bar), and the place where the operation finally needs to be performed would invoke the passed-around function (or object). I.e., f() would return foo or bar as a function value, and g() would be passed the function value and simply invoke it instead of doing the `match` case distinction.
The drawback is that it’s then less clear in some parts of the code which implementation will be invoked. But the alternative is having to invoke the specific operation (directly or indirectly) immediately when the condition is determined. It’s a trade-off that depends on the situation.
The drawback is that it’s then less clear in some parts of the code which implementation will be invoked. But the alternative is having to invoke the specific operation (directly or indirectly) immediately when the condition is determined. It’s a trade-off that depends on the situation.