🌳
Walking though the Elm woods
  • Introduction
  • Structure of the book
  • Frequently asked questions
    • How can different types share data?
    • How to break Dependency Cycles?
    • How to structure an Elm project?
    • How to turn a Msg into a Cmd Msg?
    • How to update nested Records?
    • What are comparable types?
    • Why are Booleans bad?
    • 🔜Future topics
  • Recipes
    • Writing a Single Page Application
      • Share state across pages
      • Debounced Validation
      • Reusable views
    • Making impossible states Impossible
      • Non empty lists using Zippers
      • Restrict records using Opaque Types
      • Write safer functions using Phantom Types
    • Designing Elm package APIs
      • Create upwards compatible APIs
    • 🔜Future topics
  • Frameworks and packages
    • elm/parser
    • mdgriffith/elm-ui
    • 🔜Future topics
Powered by GitBook
On this page
  • Question
  • Answer
  • Further reading

Was this helpful?

  1. Frequently asked questions

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

PreviousWhat are comparable types?NextFuture topics

Last updated 5 years ago

Was this helpful?

🎥Video: by Jeremy Fairbank

📄Article: by Jeremy Fairbank

📄Article: by Jeremy Fairbank

Solving the Boolean Identity Crisis
Solving the Boolean Identity Crisis Part 1
Solving the Boolean Identity Crisis Part 2