From fcdd6c5a79cec3a21522aa3e888512c020b53f96 Mon Sep 17 00:00:00 2001 From: Nazarii F Date: Mon, 4 Mar 2024 16:38:50 +0200 Subject: [PATCH] Added destructuring section to new-guidelines.md (#18731) Adds a section explaining the use cases of destructuring function parameters to improve code style and reduce the chance of bugs. --- src/quo/README.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/src/quo/README.md b/src/quo/README.md index 5ef3e5a7ca..3450967366 100644 --- a/src/quo/README.md +++ b/src/quo/README.md @@ -106,6 +106,32 @@ The convention is `:size-`, e.g size `20` is `:size-20` - Try to make all other vars private because they should almost never be used directly. +## Default value when destructuring + +Too often callers pass nil values because values can be wrapped in a `when` for example. +In this case, the default value is not applied, because :or macro will use default only when the value is absent. +Instead, use `(or (:value props) some-default-value)` in a `let` expression or as a parameter value. + +```clojure +;; bad (unreliable) +(defn- view-internal + [{:keys [auto-focus? + init-value + return-key-type] + :or {auto-focus? false + init-value 0 + return-key-type :done}}] + ...) + +;; good +(defn- view-internal + [{:keys [theme size something] :as props}] + (let [auto-focus? (or (:auto-focus? props) false) + init-value (or (:init-value props) 0) + return-key-type (or (:return-key-type props) :done)] + ...)) +``` + ## Component tests We don't attempt to write component tests verifying how components look on the