4 ms·
If a function returns early, its post-conditions cannot be checked.
by augustk 6y ago
If a function returns early, its post-conditions cannot be checked.
- lizmat 6y agoThis is not true in Raku: whichever way you leave a subroutine, the returned value will be checked against the return constraint. And throw if that fails. More generally, you can specify KEEP and UNDO phasers in a block, that will fire whether the block is left successfully or not. So a typical usage would be `UNDO $dbh.rollback`.
- fnord77 6y agocould you give an example of this? (all I can think of is something where you could handle it with a finally-type clause) maybe a fn shouldn't have post conditions?
- quietbritishjim 6y agoDo you mean checked by a human reader? If so, a linear sequence of if statements that return early is far easier to check than than deeply nested statements where the error handling for failures is effectively back-to-front at the end. Or are you saying that there are some lines of code at the end checking the post conditions? I'm not exactly sure what that would look like, it sounds a bit insane, especially if you do it for every function. Could you give an example?
- augustk 6y agoI mean programmatically with an assertion statement or similar. You don't want to add the same assertion before each return statement.
- darwingr 6y agoI’d love an example if you have one. I’ve used assertions lots as guards or pre-condition checks on entering the function but never right before returning.
- augustk 6y agoA complicated sorting algorithm could assert that the result is sorted before returning.
- raiph 6y agoHopefully you saw Liz's comment. Raku has a zero cost way to add arbitrary post processing that kicks in no matter where or how a block of code exits. This provides a general mechanism accessible by arbitrary user defined control flow related constructs. Raku also ships with a dozen or so built in constructs such as PRE and POST blocks that are the foundational elements for DbC, plus UNDO and KEEP blocks for transactional semantics, and so on.