📎 Webclip
How to write clean functions
The tutorial refactors a JavaScript example step by step to make the function easier to read and update. It uses the ideas of small functions, one responsibility, one level of abstraction, fewer arguments, and no side effects.
Reading notes#
- The article is inspired by Clean Code by Robert C. Martin.
- It presents a JavaScript function that initially mixes price lookup, error handling, discount logic, rounding, and a mutation on the product object.
- The first refactoring extracts discount handling into a separate function so the main function becomes smaller.
- The next step narrows the main function to the price itself and moves error handling to the caller.
- The article then removes rounding details from the main function by replacing inline arithmetic with a helper.
- It argues that functions are easier to reason about when they take fewer arguments, ideally zero, one, or two.
- To reduce arguments, it turns the discount logic into a fraction and then separates coupon validity from price reduction.
- It identifies the mutation of
product.userCheckedPriceas a side effect and recommends moving that update outside the price function. - The final version of
getProductPriceonly gets the price, applies a fraction, and rounds the result.
