# Guard Clauses

Sometimes, you will want to not run your code in a certain situation. Instead of nesting the code in an if statement, you can reverse condition and put the if statement prior to the code. This backwards if statement is known as a guard clause.

{% code overflow="wrap" lineNumbers="true" %}

```java
function buy(player: player, item: item, price: number):
  if {_player}'s balance >= {_price}:
    remove {_price} from {_player}'s balance
    give {_player} {_item}
    send "You bought %{_item}% for %{_price}%" to {_player}

  else:
    send "You cannot afford this!" to {_player}
```

{% endcode %}

Since the else section is much shorter and doesn't involve the main segment of code, its easier to just get it out of the way first.

{% code overflow="wrap" lineNumbers="true" %}

```java
function buy(player: player, item: item, price: number):
  if {_player}'s balance < {_price}:
    send "You cannot afford this!" to {_player}
    stop

  remove {_price} from {_player}'s balance
  give {_player} {_item}
  send "You bought %{_item}% for %{_price}%" to {_player}
```

{% endcode %}

Notice how the code no longer checks if the player's balance is greater than or equal to the price, but now less than the price. This is because the new code is essentially turning the old else section into an if statement.

See how the stop allows the main code to be un-nested one level? One level might not seem like much, but it can add up if you turn multiple if statements into guard clauses. Having the stop before the central code also allows for more intuitive logic flow, making the code much easier to read through.

{% hint style="info" %}
Not sure what the stop effect does? Check out the \[LINK: Limiters>Stops page].
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://x8ight.gitbook.io/syntask/organisation/never-nesting/if-statements/guard-clauses.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
