For the complete documentation index, see llms.txt. This page is also available as Markdown.

Why are Booleans bad?

type alias Request =
    { fetching : Bool
    , error : String
    , message : String
    }

getResponse : Request -> ( String, Bool )
getResponse request =
    if request.fetching then
        ( "", True)
    else if error == "" then
        ( request.message, True )
    else
        ( request.error, False )
type Request =
    Fetching
    | Error String
    | Message String

getResponse : Request -> Maybe (Result String String)
getResponse request =
    case request of
        Fetching ->
            Nothing
        Error error ->
            Just <| Err error
        Ok message ->
            Just <| Ok message

Question

I heard that Booleans should be avoided in Elm, How and Why?

Answer

Booleans create a lot of problems, for example what does it mean if Request.fetching is False but Request.message has some value? Or how can one know what the returned boolean of getResponse stands for? The type system of Elm can avoid such problems:

  • Use Maybe (String, Bool) instead of returning some default value.

  • Use Result String String to handle results

  • Use a Custom Type and Patter Matching instead of Request.fetching and If-Statements.

Further reading

Last updated