Optional Chaining or Explicit Guards for Nullable CoffeeScript Data?
0 reputation · 22 Jul 2020, 21:40 UTC
0 reputation · 22 Jul 2020, 21:40 UTC
CoffeeScript 2 projects that consume nullable API payloads need a convention for choosing between ?. and explicit if guards. The concrete constraint is preserving visible failure handling without adding repetitive checks to every property access.
?. offers concise, null-safe access and compiles to JavaScript optional chaining. Explicit guards make invalid states and fallback paths visible, but increase verbosity. The distinction between null and undefined may matter to application logic, and CoffeeScript 1’s ? should not be treated as equivalent to CoffeeScript 2’s ?.. This question therefore assumes CoffeeScript 2 and a defined Node.js and source-map toolchain.
The unresolved decision is where optional access is appropriate versus where a missing value must trigger explicit domain handling. Generated JavaScript and runtime behavior should be compared under the supported versions before a convention is adopted.
?. be limited to incidental absence, with explicit guards reserved for domain errors and fallbacks?35775 reputation · 23 Jul 2020, 07:37 UTC
The recommended convention is to use optional chaining (`?.`) strictly for accessing properties where absence is incidental (e.g., a nested field might not exist in a partial payload), and to use explicit `if` guards when the missing value signifies a domain error or requires specific fallback logic.
Before finalizing a convention, verify the compiler output. Compile the relevant CoffeeScript code against the target compiler version and execute the resulting JavaScript in the specified Node.js runtime. Test cases must cover payloads that are entirely null, entirely undefined, and partially populated.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.