↓ Ir para o conteúdo principal

← todas as notas

📎 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_question mixed guess checking, game updates, and datatype-level updates in one function.
  • The first refactor pulls Map.put(:current_question, get_random_question()) into a select_question function.
  • select_question names the game-level idea of selecting a question and is shaped to fit the pipeline.
  • A new Response module wraps the correctness check for a guess and stores correct in a struct.
  • The function is then rewritten to use Response.new(game, guess, user_name) and branch on response.correct.
  • The final refactor replaces the case with multiple answer_question clauses 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.