Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> Pushing "ifs" up has the downside that the preconditions and postconditions are no longer directly visible in the definition of a function

You're missing the second part of the author's argument:

"or it could push the task of precondition checking to its caller, and enforce via types"

The precondition is therefore still directly visible in the function definition - just as part of the type signature rather than in an if statement.

The "enforce preconditions via types" is a common pattern in Rust (the language used in the article), and unlike checking with if statements, it's a strict precondition that is checked at compile time rather than at runtime and you won't even be able to compile your program if you don't meet the pre-condition.



> The "enforce preconditions via types" is a common pattern in Rust

Called the Type State Pattern. Here are two links from my bookmarks:

https://cliffle.com/blog/rust-typestate/

https://yoric.github.io/post/rust-typestate/


Definitely, that's a pattern in many programming languages (including, increasingly, in Python). And in dependently-typed languages, you actually can obtain a proof of validity that gets erased at runtime, leaving nothing but basic unboxed data to be executed.

However that's not always an option in all languages or situations, and it's hard to encode conditions like "must only be called while an event loop is running" that way.

I'm envisioning this partly as kind of a catch-all/fallback mechanism that can either be bolted on a language that doesn't have these kinds of features. But it's not always the case that you can effectively communicate contextual requirements through the types of function parameters, and this would cover that case as well.

If you want to reduce this to anything, it's a workaround for not having monads in your language, with some tradeoffs around composability and dynamic extent.


> "or it could push the task of precondition checking to its caller, and enforce via types"

Or the enforcement could be done via a design-by-contract discipline. Either using classical assertions, or something like reusable specifications in Clojure's spec library.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: