0
0
Blockchain / Solidityprogramming~5 mins

Short-circuiting in conditions in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

Short-circuiting helps your program skip unnecessary checks to save time and avoid errors.

When you want to check if a user has enough balance before allowing a transaction.
When you want to verify multiple conditions but stop as soon as one fails.
When you want to avoid errors by not running code that depends on earlier checks.
When you want to improve performance by not doing extra work if not needed.
Syntax
Blockchain / Solidity
if (condition1 && condition2) {
    // code runs if both are true
}

if (condition1 || condition2) {
    // code runs if at least one is true
}

In &&, if the first condition is false, the second is not checked.

In ||, if the first condition is true, the second is not checked.

Examples
This checks if the user has money and is verified. If the balance is zero, it skips checking verification.
Blockchain / Solidity
if (userBalance > 0 && userIsVerified) {
    // allow transaction
}
This allows access if the user is either the owner or an admin. If the user is owner, it skips checking admin.
Blockchain / Solidity
if (isOwner || isAdmin) {
    // allow access
}
This avoids errors by checking if user exists before checking if active.
Blockchain / Solidity
if (user != null && user.isActive) {
    // safe to use user
}
Sample Program

This smart contract checks if a user can spend money only if they have enough balance and are verified. The second check is skipped if balance is low.

Blockchain / Solidity
pragma solidity ^0.8.0;

contract ShortCircuitExample {
    uint public balance = 100;
    bool public isVerified = false;

    function canSpend(uint amount) public view returns (bool) {
        // Check if balance is enough and user is verified
        if (balance >= amount && isVerified) {
            return true;
        } else {
            return false;
        }
    }

    function test() public view returns (string memory) {
        if (canSpend(50)) {
            return "Allowed to spend 50";
        } else {
            return "Not allowed to spend 50";
        }
    }
}
OutputSuccess
Important Notes

Short-circuiting helps avoid errors like checking properties of a null object.

It can make your code faster by skipping unnecessary checks.

Summary

Short-circuiting stops checking conditions as soon as the result is known.

Use && to require all conditions true, and || to require any condition true.

This helps avoid errors and improve performance in your blockchain code.