Why are Booleans bad?
Problem
Solution
1
type alias Request =
2
{ fetching : Bool
3
, error : String
4
, message : String
5
}
6
​
7
getResponse : Request -> ( String, Bool )
8
getResponse request =
9
if request.fetching then
10
( "", True)
11
else if error == "" then
12
( request.message, True )
13
else
14
( request.error, False )
Copied!
1
type Request =
2
Fetching
3
| Error String
4
| Message String
5
​
6
getResponse : Request -> Maybe (Result String String)
7
getResponse request =
8
case request of
9
Fetching ->
10
Nothing
11
Error error ->
12
Just <| Err error
13
Ok message ->
14
Just <| Ok message
Copied!

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