The Ladder of Intent
Assembly consists of direct instructions to CPU. The code says exactly what happens and nothing about what you are trying to achieve. Command is a command, a JMP is a jump. Only reading the code around the jump and the landing location, and also in between, gives you a clue about the intent of the jump.
If we climb our ladder higher, to C language, which is very low level by today’s standards, it starts to discern small amounts of intent. Jump is not just a jump, it can be an if, a for loop or a function. Variables and blocks of code (functions) get names. I think the whole story about GOTO considered harmful is about the absolute lack of intent.
Let’s climb higher again, to Python. Python is a much higher level language than C. It achieves this mainly by offering “looseness” (dynamic typing) and higher level / heterogeneous data structures. But it still has if, while, for loops, like C had. It worked on ergonomics a lot, maybe less on intent.
It seems our ladder is in reality a tree, and we swing to a parallel FP branch. Here, the what of for, while and until is replaced by the why of map, filter and reduce. These languages are less loose (more static) than Python, but in another way also more high level because they moved the intent needle forward.
Even an ergonomic for loop is just a loop, and like in Assembly, you have to read the code inside it, and perhaps around it, to discern the what and why. filter, map and reduce signal the intent much better.
I sit here thinking about failure
I’m a practical man, solving real-world problems, and in the real world, things fail with a greater than zero probability. Rye language that I’m building is big on moving even closer to human, being even more high-level. That means it tries to make intent visible across all core mechanisms, and failure handling is a big one.
But in general, failure handling remained at the level of an ergonomic for loop. Intent is not signaled, it has to be discerned by reading the code.
And just like map, filter and reduce solve a lot of data transformation boilerplate, there should be a set of high-intent signaling primitives for handling failure.
Below is what I, somewhat organically over several years, came up with. Feedback and outside perspective would be beneficial at this point, hence this blogpost …
Three patterns we will look at: add context to failure and pass up, create failure and pass up, recover and continue
Precursor: two Rye specifics
Code below might seem odd to you. But it could be odd just because you don’t yet know about the concepts it uses.
First is pipe-words, which look like this |print. It means that if we write function name as a pipe-word, the function, in this case print, takes the first argument from the left.
; these two do the same
print "Hello!"
"Hello!" |print ; both print Hello!
; And these two
head "butterfly" 3
"butterfly" |head 3 ; both result in "butter"
; you can string them together
upper "butterfly" |tail 3 |concat "!" |print ; prints FLY!
Second: Most languages return from a function using something like return keyword. Rye has no keywords and uses implicit return. But it does have a return function.
So it can have other functions that do the returning. We call them returning functions. Since it’s a very specific behaviour these functions all start with ^, so they are very noticable in code.
A common pattern of return early in Go:
if role == 'admin' {
return "go away"
}
can in Rye look like this.
^if role = 'admin' { "go away" }
That itself doesn’t seem worth adding a new concept to a language. But returning functions do make their worth with Error handling.
Check, wrap and return
we will look at this pattern for majority of the remaining article
The most useful pattern of error handling in Rye is simply called ^check. It’s a function that accepts two arguments: first, a value it checks and second, content for potential failure construction
Failure object in Rye can be constructed with a string (message), but also integer (status code), word (type), a parent failure or a combination of these.
So it works like this. If the first argument is a failure, it wraps that failure with a new failure it constructs from the second argument and returns that to caller (returns from current function). If not, it just passes the first argument forward.
integer port-str
|^check "couldn't parse port"
|print
In Go this would be:
port, err := strconv.Atoi(portStr)
if err != nil {
return 0, fmt.Errorf("parse port: %w", err)
}
fmt.Println(port)
Please note, that both code snippets are to be inside a function, they both return to caller / exit the function in case of a failure, otherwise continue.
If port-str is "8080" code just prints 8080. And if it is for example "80XY" Rye exits, returns to caller
with the following two level failure:
Error: couldn't parse port
Error: integer: strconv.Atoi: parsing "80XY": invalid syntax
So why do I say this is the most composable pattern and why a returning function? Because we are in most cases in a function that doesn’t really have the authority to decide what to do about the failure it observed. So the best thing to do is often to translate (wrap) the failure into a higher level (the level of the function) failure and return that. TLDR: Do you want your tire sensor failing have the ability to shut down your whole car while cruising down the highway?
We now looked at the check and wrap part, but to see the return part we should show this in a chain of functions that really do some returning.
get-json: fn { file } {
.Read
|^check "Couldn't read JSON file"
|parse-json
|^check "File contains invalid JSON"
}
get-name: does {
get-json %user.json
|^check "Problem loading user data"
|-> "name"
|^check "Missing name field in user data"
}
hello-name: does {
get-name
|^check "Couldn't get name to say hello to"
|printv "Hello {}!"
}
hello-name
Let’s test few scenarios now and see what we get:
- user file is there but you don’t have permissions to read it
Error: Couldn't get name to say hello to
Error: Problem loading user data
Error: Couldn't read JSON file
Error: file-uri//Read: open user.json: permission denied
- file is there and readable, but it contains malformed JSON
Error: Couldn't get name to say hello to
Error: Problem loading user data
Error: File contains invalid JSON
Error: parse-json: Failed to parse JSON: invalid character 'x' after object key:value pair
- user data is readable, is valid JSON, but doesn’t contain name field
Error: Couldn't get name to say hello to
Error: Missing name field in user data
Error: Key 'name' not found in dict
- user data is readable, valid JSON and contains
"Jason"innamefield
Hello Jason!
We mentioned that check does the translation of Failure from a lower (computer) to a higher (function appropriate) level (towards the user level).
And returns to the caller.
With this in mind, let’s analyze the Scenario 1.
get-jsonknows it should get JSON from a file. It doesn’t know or care what the JSON’s role is. It reads the file and parses JSON. If it can’t do that it fails with information on the task that wraps the lower level failure, which holds more technical information (a filename, error type or concrete JSON parsing error)get-nameknows it’s usingget-jsonon a JSON file to get information from which it extracts thenamefield. Again if it fails it reports it wrapping the lower failures, not losing any information, but also not assuming below or above its level.hello-nameknows that it needs a name and why, adds final context
Ensure, or return with failure
The next construct is simpler, and doesn’t react to failure, but in fact creates a failure and returns to the caller.
^ensure function accepts a boolean, fails and returns to caller if the value is false.
Rye example:
user-age > 0 |^ensure "age must be positive"
Similar in Go:
if userAge <= 0 {
return fmt.Errorf("age must be positive")
}
It’s a simple but useful function that ties nicely with other failure handling. It also has a variation that fits Rye’s left to right flows:
Request http://example.com 'GET "" |Call
|^ensure\with { .Status? = 200 } "request failed"
|Read-body |html->markdown
Fix a failure, continue
The third pattern, also a nice, simple one, is a fix function. This one is non-returning although returning variant also exists.
1 / 0 |fix { 0 } ; results in zero
{ } |avg |fix { 50 } ; avg doesn't decide what to do when
; there is no data to avg, fix can
D{ score: 230 } -> "name" |fix { "Anon" } ; BTW: Rye has no null (no third state)
; only success or failure
; which we can (in fact must) fix :)
Or a little more involved example
config: load-config "app.yml" |fix { default-config }
which would in Go be:
config, err := loadConfig("app.yml")
if err != nil {
config = defaultConfig()
}
Sometimes you want to fix based on type of error, so there are fix\either and fix\switch for example, but the pattern is similar.
Putting these together
We use our example from above, but now our script also ensures that the name field is not empty. And if anything goes wrong with getting the name, we can fix it, instead of failing. We log the error and say hello to Anonymous.
get-json: fn { file } {
.Read
|^check "Couldn't read JSON file"
|parse-json
|^check "File contains invalid JSON"
}
get-name: does {
get-json %user.json
|^check "Problem loading user data"
|-> "name"
|^check "Missing name field in user data"
|^ensure\with { .is-empty .not } "Name is empty"
}
hello-name: does {
get-name
|fix { .log/failure , "Anonymous" }
|printv "Hello {}!"
}
log: context {
failure: fn1 { .fmt-fail |Append* %my.log }
fmt-fail: fn { e } { join map [ now n e n ] ?string }
n: "\n"
}
hello-name
If you will want to know what’s up with the context, dots, stars and question marks, you will just have to Meet Rye :)
Outro
I’m not trying to introduce a new error-handling mechanism or compare the existing ones. Exceptions, Result types, errors as values have been discussed elsewhere. I’m interested is what could be a base vocabulary that expresses what we intend to do around failure. So my vocab became:
- ^check “not my call, I check for failure, add context and pass it up.”
- ^ensure “ensure a condition, if needed create a failure and pass it up.”
- fix “this is my call, I recover from failure and continue the code”
So what do you think? The list is not exhaustive like we can’t reduce everything to map, filter and, well, reduce; but words usually solved me a great deal of needs in a nice, composable and high-intent way. Does this make sense to you? Do you see different patterns, perhaps propose different vocabulary? Feedback welcome.
I will post this on Lobste.rs for one, otherwise visit Homoiconic Discord for further discussion.