0
0
Blockchain / Solidityprogramming~15 mins

If-else statements in Blockchain / Solidity - Deep Dive

Choose your learning style9 modes available
Overview - If-else statements
What is it?
If-else statements are a way to make decisions in a program. They check if a condition is true or false, then run different code based on that. This helps the program choose what to do next. It is like asking a question and acting on the answer.
Why it matters
Without if-else statements, programs would do the same thing all the time, no matter what. This would make blockchain contracts and apps unable to react to different situations, like checking if a user has enough tokens before sending money. If-else lets programs be smart and flexible.
Where it fits
Before learning if-else, you should know what variables and basic expressions are. After if-else, you can learn about loops and functions to make programs more powerful and reusable.
Mental Model
Core Idea
If-else statements let a program choose between two or more paths based on conditions.
Think of it like...
It's like a traffic light that tells cars to stop or go depending on the color. The program checks the 'light' and decides what to do next.
┌───────────────┐
│ Check condition│
└──────┬────────┘
       │True
       ▼
  ┌───────────┐
  │ Run 'if'  │
  │  block    │
  └───────────┘
       │
       ▼
     End
       ▲
       │False
  ┌───────────┐
  │ Run 'else'│
  │  block    │
  └───────────┘
Build-Up - 6 Steps
1
FoundationUnderstanding basic condition checks
🤔
Concept: Learn how to write a simple condition that checks if a value meets a rule.
In blockchain programming, you often check if a number is greater than another. For example, checking if a user's balance is more than 10 tokens. This uses comparison operators like >, <, ==.
Result
You can write expressions that return true or false, like 'balance > 10'.
Understanding how to check conditions is the base for making decisions in code.
2
FoundationWriting a simple if statement
🤔
Concept: Use an if statement to run code only when a condition is true.
Example in Solidity (a blockchain language): if (balance > 10) { // allow transfer } This means the code inside runs only if balance is more than 10.
Result
Code inside the if block runs only when the condition is true.
Knowing how to run code conditionally lets your program react to different states.
3
IntermediateAdding else for alternative actions
🤔Before reading on: do you think else runs when the if condition is true or false? Commit to your answer.
Concept: Use else to run code when the if condition is false.
Example: if (balance > 10) { // allow transfer } else { // reject transfer } If balance is not more than 10, the else block runs.
Result
One of the two blocks runs depending on the condition.
Using else ensures your program handles both yes and no cases clearly.
4
IntermediateUsing else if for multiple choices
🤔Before reading on: do you think else if can check more than one condition in order? Commit to your answer.
Concept: Use else if to check several conditions one after another.
Example: if (balance > 100) { // VIP transfer } else if (balance > 10) { // normal transfer } else { // reject transfer } The program checks each condition in order until one is true.
Result
The first true condition's block runs; others are skipped.
Chaining conditions lets your program choose from many options, not just two.
5
AdvancedNested if-else for complex decisions
🤔Before reading on: do you think nested if-else can make decisions inside decisions? Commit to your answer.
Concept: Put if-else statements inside other if-else blocks to handle detailed cases.
Example: if (balance > 10) { if (isVerified) { // allow transfer } else { // require verification } } else { // reject transfer } This checks verification only if balance is enough.
Result
Decisions can be layered to handle complex rules.
Nesting lets your program handle detailed and dependent conditions step by step.
6
ExpertGas cost and short-circuiting in if-else
🤔Before reading on: do you think all conditions in if-else chains always run? Commit to your answer.
Concept: In blockchain, conditions cost gas (money) to check; if-else stops checking once a true condition is found.
Example: if (balance > 1000) { // expensive check } else if (balance > 10) { // cheaper check } Only the first true condition runs, saving gas. Writing conditions from most likely to least saves money.
Result
Efficient if-else ordering reduces transaction costs.
Knowing how if-else short-circuits helps write cheaper, faster blockchain code.
Under the Hood
When the program reaches an if-else statement, it evaluates the condition inside the if first. If true, it runs the code inside that block and skips the rest. If false, it checks else if conditions in order or runs the else block if no conditions are true. This decision-making happens step-by-step during execution, controlling the program flow.
Why designed this way?
If-else was designed to let programs make choices like humans do, with simple yes/no questions. It avoids running unnecessary code by stopping at the first true condition, which is important in blockchain to save gas and keep transactions efficient.
Start
  │
  ▼
[Evaluate condition]
  │
  ├─True─►[Run if block]─►End
  │
  └─False─►[Check else if or else]
            │
            ├─True─►[Run else if block]─►End
            │
            └─False─►[Run else block]─►End
Myth Busters - 4 Common Misconceptions
Quick: Does else run when the if condition is true? Commit yes or no.
Common Belief:Else runs after if no matter what.
Tap to reveal reality
Reality:Else runs only if the if condition is false.
Why it matters:Running else when if is true causes wrong program behavior and bugs.
Quick: Can multiple if blocks run in a chain of if-else if-else? Commit yes or no.
Common Belief:All if and else if blocks run if their conditions are true.
Tap to reveal reality
Reality:Only the first true condition's block runs; others are skipped.
Why it matters:Expecting multiple blocks to run can cause logic errors and unexpected results.
Quick: Does nesting if-else mean the inner if runs regardless of outer if? Commit yes or no.
Common Belief:Inner if-else always runs even if outer if is false.
Tap to reveal reality
Reality:Inner if-else runs only if the outer if condition is true and its block executes.
Why it matters:Misunderstanding nesting leads to wrong assumptions about code execution paths.
Quick: Do all conditions in if-else chains always get evaluated? Commit yes or no.
Common Belief:Every condition in if-else chains is checked every time.
Tap to reveal reality
Reality:Evaluation stops at the first true condition (short-circuiting).
Why it matters:Ignoring short-circuiting can cause inefficient code and higher blockchain gas costs.
Expert Zone
1
Ordering conditions from most to least likely true saves gas and improves performance in blockchain.
2
Using nested if-else can increase code complexity and gas cost; sometimes combining conditions is better.
3
Short-circuiting behavior can be leveraged to avoid expensive checks when simpler conditions fail.
When NOT to use
If-else is not ideal for many repeated checks or complex state machines; use switch statements or mapping structures instead for clarity and efficiency.
Production Patterns
In smart contracts, if-else is used to validate user permissions, check balances, and enforce rules before executing transactions, often combined with require statements for safety.
Connections
Boolean Logic
If-else statements rely on boolean logic to decide true or false conditions.
Understanding boolean logic helps write clearer and more accurate conditions in if-else statements.
Decision Trees (Data Science)
If-else chains resemble decision trees that split data based on conditions.
Seeing if-else as a decision tree helps understand complex branching and multiple condition handling.
Human Decision Making (Psychology)
If-else mimics how humans make choices by evaluating conditions and picking actions.
Recognizing this connection shows how programming models real-world thinking processes.
Common Pitfalls
#1Writing else without if causes syntax errors.
Wrong approach:else { // code }
Correct approach:if (condition) { // code } else { // code }
Root cause:Else must always follow an if; forgetting this breaks the program.
#2Using = instead of == in condition causes assignment, not comparison.
Wrong approach:if (balance = 10) { // code }
Correct approach:if (balance == 10) { // code }
Root cause:Confusing assignment (=) with equality check (==) leads to wrong logic and bugs.
#3Not covering all cases leads to unexpected behavior.
Wrong approach:if (balance > 10) { // allow } // no else block
Correct approach:if (balance > 10) { // allow } else { // reject }
Root cause:Missing else means program does nothing when condition is false, causing errors.
Key Takeaways
If-else statements let programs choose actions based on conditions, making code flexible and smart.
Only one block in an if-else chain runs: the first true condition's block, or else if none are true.
Nesting if-else allows detailed decisions but can increase complexity and cost in blockchain.
Short-circuiting in if-else saves resources by stopping checks early, important for blockchain efficiency.
Common mistakes include confusing assignment with comparison and missing else blocks, which cause bugs.