📎 Webclip
Refactoring a Function in Elixir
The post revisits a quiz game’s answer_question function and refactors it to follow core programming principles from Designing Elixir Systems with OTP. The goal is to make the function easier to understand by reducing abstraction layers and by breaking out small, focused pieces of behavior.
Reading notes#
- The original
answer_questionmixed guess checking, game updates, and datatype-level updates in one function. - The first refactor pulls
Map.put(:current_question, get_random_question())into aselect_questionfunction. select_questionnames the game-level idea of selecting a question and is shaped to fit the pipeline.- A new
Responsemodule wraps the correctness check for a guess and storescorrectin a struct. - The function is then rewritten to use
Response.new(game, guess, user_name)and branch onresponse.correct. - The final refactor replaces the
casewith multipleanswer_questionclauses that pattern match on%Response{correct: true}and%Response{correct: false}. - The author says these changes make the function’s intention clearer, and the code more testable and maintainable over time.
