A Zoo vending machine needs to explain why a purchase was rejected or confirm that it is ready. There may be several possible responses, but one purchase attempt should receive one response. An if/else if chain expresses that choice.
An if begins the chain. Each else if supplies another condition to consider only when the earlier conditions were false. An optional else handles everything left over. After one branch runs, execution continues after the entire chain.
This makes order part of the rule. When more than one condition could be true, the earlier one has priority. The later conditions are not evaluated once a branch has been selected.
public string GetPurchaseMessage(decimal payment, int portionsAvailable)
{
string message;
if (portionsAvailable <= 0)
{
message = "No food available";
}
else if (payment < 2.00m)
{
message = "More payment needed";
}
else
{
message = "Ready to purchase";
}
return message;
}The method checks availability first, then payment. It reports readiness only when neither rejection condition applies. This method describes the result; it does not deduct money or remove food. That lets you reason about the decision before adding transaction changes.
| Available portions | Payment | Checks performed | Returned message |
|---|---|---|---|
| 0 | 1.00 | Availability only | No food available |
| 4 | 1.00 | Availability then payment | More payment needed |
| 4 | 2.00 | Availability then payment | Ready to purchase |
In the first row, both shortage conditions would be true, but the availability response wins. In the last row, payment equal to the price is sufficient because payment < 2.00m is false. The fallback branch does not have its own condition.
Separate if statements each make an independent decision. Replacing else if with another if can allow several bodies to run, and a final else belongs only to the immediately preceding if. A later assignment might overwrite the message chosen earlier.
Use a chain when the requirement says to choose one outcome. Keep independent if statements when several independent actions really should happen during the same operation.
Predict the message for zero available portions and a payment of 5.00. Then predict it for four portions and a payment of 1.99. Name the first true condition in each attempt before checking the table.
Now imagine that the requirement changes to report insufficient payment before unavailable food. Which two checks would you reorder, and which test would expose that change?