Master if expressions, loops, and error handling with assert and abort
In Move, 'if' is an expression that returns a value! Both branches must return the same type. This is different from many languages where if is just a statement.
When using if to return a value: 1) Condition in parentheses 2) Both branches in braces 3) Both must return SAME type 4) Else is required
You can nest if expressions inside each other for complex decision trees. Each level can return different values based on multiple conditions.
While loops repeat code as long as a condition is true. Great for counting, searching, or repeating until a goal is reached.
Use 'loop' for infinite loops. Use 'break' to exit when you're done. Useful when you don't know in advance how many iterations you need.
Use 'continue' to skip the rest of the current iteration and jump to the next one. Perfect for skipping unwanted values.
WARNING: Infinite loops can lock up blockchain transactions! Always ensure loops terminate. Smart contract platforms limit execution time (gas). Design loops carefully!
Use assert! to check preconditions - things that must be true for your function to work correctly. If the check fails, the program aborts with your error code.
Use 'abort' to explicitly fail with an error code. Unlike assert, you use abort in response to runtime conditions or invalid state, not just preconditions.
ASSERT for programmer errors (preconditions): amount > 0, caller is admin. ABORT for user/state errors (expected failures): insufficient balance, item not found.
Use meaningful error codes (constants). Document what each code means. This helps debugging when things fail. Start from 0 or use descriptive names.