Chapter 5. Strings
Étude 5-1: Validating Input
The Elixir philosophy is “let it crash”; this makes a great deal of sense for a telecommunications system (which is what Elixir was first designed for). Hardware is going to fail. When it does, you just replace it or restart it. The person using the phone system is unaware of this; her phone just continues to work.
This philosophy, however, is not the one you want to employ when you have (atypical for Elixir) programs that ask for user input. You want to those to crash infrequently and catch as many input errors as possible.
In this étude, you will write a module named ask_area
, which prompts you
for a shape and its dimensions, and then returns the area by calling
Geom.area/3
, which you wrote in Étude 4-1.
Your module will ask for the first letter of the shape (in either upper or lower case), then the appropriate dimensions. It should catch invalid letters, non-numeric input, and negative numbers as input. Here is some sample output.
iex(1)> c("ask_area.ex") [AskArea] iex(2)> c("geom.ex") [Geom] iex(3)> AskArea.area() R)ectangle, T)riangle, or E)llipse: r Enter width > 4 Enter height > 3 12 iex(4)> AskArea.area() R)ectangle, T)riangle, or E)llipse: T Enter base > 3 Enter height > 7 10.5 iex(5)> AskArea.area() R)ectangle, T)riangle, or E)llipse: w Unknown shape w :ok iex(6)> AskArea.area() R)ectangle, T)riangle, or E)llipse: r Enter width > -3 Enter height > 4 Both numbers must be greater than or equal to zero. :ok iex(7)> AskArea.area() ...
Get Études for Elixir now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.