Thursday, April 30, 2026

Simpler code with early returns: "Guard Clauses"

This is how "ideomatic Go" (or any other code) should like, simpler.

Guard Clauses: Simplifying Code with Early Returns | by Vaibhav Mojidra | Medium

Guard clauses (or early returns) are conditional statements placed at the beginning of a function that exit early if specific conditions are not met, reducing nested if-else structures. They improve readability by separating error handling and validations from the main logic

JS

function
getMemberDiscount(member) { if (member) { if (member.isPremium) { return "20% off"; } else { return "10% off"; } } else { return "No discount"; } }

=>
function getMemberDiscount(member) {
  // Guard clauses
  if (!member) return "No discount";
  if (!member.isPremium) return "10% off";
  // Main logic (no nesting)
  return "20% off";
}

In modern programming languages like C#, Java, and Dart, guard clauses can be used within switch expressions to add additional conditions to a pattern match. These are often called case guards or when clauses.