Stream: beginners

Topic: this should never happen


view this post on Zulip Anton (Jan 29 2024 at 19:17):

In packages and platforms, there are cases like below where results should always be Ok something, but as code is edited over time you can definitely screw things up. This makes me wonder if it's not better to crash in cases like this, thereby making it a lot easier to notice when it did get screwed up.

if isValidUtf8Byte byte then
    Str.toUtf8 string
    |> List.append byte
    |> Str.fromUtf8
    |> Result.withDefault "" # This will never fail

view this post on Zulip Brendan Hansknecht (Jan 29 2024 at 19:26):

If it should truly be impossible, never use a default

Crash or return an error tag anyways. That's my opinion.

view this post on Zulip Brendan Hansknecht (Jan 29 2024 at 19:27):

That said, your function above should probably be rewritten

view this post on Zulip Brendan Hansknecht (Jan 29 2024 at 19:28):

when Str.toUtf8 string |> List.append byte |> Str.fromUtf8 is
     Ok str -> str
     Err _ -> -- do whatever the false case of the if expression above does

view this post on Zulip Brendan Hansknecht (Jan 29 2024 at 19:29):

Actually, after writing this out, I am not 100% sure this should be written this way. It will be slower on the error case.

view this post on Zulip Brendan Hansknecht (Jan 29 2024 at 19:30):

So I would say, for this example, due to perf reasons, probably should just stay the same as the original code but crash.

view this post on Zulip Brendan Hansknecht (Jan 29 2024 at 19:30):

Aside, crashing should actually optimize better than using a default.

view this post on Zulip Brian Carroll (Jan 30 2024 at 07:10):

Surely it doesn't matter if it's slow in the error case, when that's never expected to happen?

view this post on Zulip Anton (Jan 30 2024 at 09:44):

Perhaps for the case of a missed branch prediction?

view this post on Zulip Brendan Hansknecht (Jan 30 2024 at 16:13):

when that's never expected to happen?

I'm not sure that's the case here, the else branch was omitted.
Str.fromUtf8 will never fail if we checked the byte was valid.

By changing to the code I shared above, the Err _ would match the else branch that we don't see in the above code. So it does not match the # This will never fail part of the code.

view this post on Zulip Brendan Hansknecht (Jan 30 2024 at 16:14):

@Anton is this just for Url.roc or is it used elsewhere?

view this post on Zulip Anton (Jan 30 2024 at 16:16):

This is indeed just for Url.roc

view this post on Zulip Brendan Hansknecht (Jan 30 2024 at 16:29):

Then we have a separate solution for the full function that already was applied to basic CLI. So should be good.


Last updated: Jul 06 2025 at 12:14 UTC