# Guard clauses

> Checking that preconditions hold before executing the logic. One form of tidying.

Checking that [preconditions](https://wiki.g15e.com/en/pages/Precondition.txt) hold before executing the logic. One form of [tidying](https://wiki.g15e.com/en/pages/Tidying.txt).

For example, changing this code…

```typescript
if (condition0)
	if (!condition1)
		doSomething()
```

…into this.

```typescript
if (!condition0) return
if (condition1) return

doSomething()
```

However, if a routine has more than seven or eight guards, a different intervention may be needed.

Meanwhile, on the claim that a function should have only one `return`:

> The "rule" about having a single return for a routine came from the days of FORTRAN, where a single routine could have multiple entry and exit points. It was nearly impossible to debug such code. You couldn't tell what statements were executed. Code with guard clauses is easier to analyze because the preconditions are explicit. --[Tidy first? A personal exercise in empirical software design](https://wiki.g15e.com/en/pages/Tidy%20First%20-%20A%20personal%20exercise%20in%20empirical%20software%20design.txt)

## Swift

[Swift](https://wiki.g15e.com/en/pages/Swift%20(programming%20language.txt)) [explicitly supports guards](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/statements/#Guard-Statement).

```swift
guard condition else {
  statements
}
```

## TypeScript

In [TypeScript](https://wiki.g15e.com/en/pages/TypeScript.txt), user-defined type predicates and type guards can assist <type inference>.[^1]

## Footnotes

[^1]: https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates