Best practice for using assert?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Assertions are debugging checks that verify assumptions about your program's internal state. Use assert to catch programmer errors (bugs) during development, not to validate user input or handle expected runtime conditions. Assertions can be disabled in production (python -O, C/C++ NDEBUG), so code must never depend on them for correctness. The core rule: if the condition can legitimately be False due to external factors (bad input, network failure, missing file), use error handling instead of assert.
Basic Assertion Syntax
Python
JavaScript (Node.js)
C/C++
Java
When to Use Assert
1. Internal Invariants
2. Preconditions on Internal Functions
3. Postconditions (Verify Results)
4. Class Invariants
When NOT to Use Assert
Do Not Validate User Input
Do Not Check External Conditions
Do Not Use for Flow Control
Assertions Are Removed in Production
Assert with Side Effects (The Biggest Mistake)
Never put code with side effects inside an assert statement. When assertions are disabled, the entire expression is removed.
Testing Frameworks and Assert
In test code, assertions are the primary verification mechanism. Testing frameworks typically never disable assertions.
Common Pitfalls
- Side effects in assert:
assert data.save()does nothing in production with optimizations enabled. The.save()call is completely removed. Always separate side effects from assertions. - Asserting on user/external input: Users can send any data. Files can be missing. Network calls can fail. These are not programming errors — they are expected conditions that need proper error handling (
ValueError,FileNotFoundError,try/catch). - Forgetting assertions are disabled: Python's
-Oflag, C'sNDEBUG, and Java's default mode all disable assertions. If your program depends onassertto prevent dangerous operations, those checks vanish in production. - Assertions as documentation instead of code:
assert x > 0is not a substitute for a docstring or type hint. Use type annotations (x: int) and docstrings for documentation, andassertonly for runtime invariant checking during development. - Performance-heavy assertions:
assert sorted(huge_list) == huge_listsorts the entire list just to verify it is sorted. Use lightweight checks or add a flag to skip expensive assertions:assert not DEBUG_SLOW or is_sorted(data).
Summary
- Use
assertfor internal invariants, preconditions on private functions, and postconditions — things that should never fail if your code is correct - Never use
assertfor input validation, external conditions, or error handling — these needif/raise/try/catch - Never put side effects inside
assert— the entire expression is removed when assertions are disabled - Assertions can be disabled in production: Python
-O, C/C++NDEBUG, Java without-ea - In testing, assertions are the primary tool — frameworks like pytest enhance
assertwith detailed failure messages - The rule of thumb: if the failure indicates a bug in your code, use
assert; if it indicates bad input or environment, use exceptions
Related reading
- Best practices for catching and re-throwing .NET exceptions
- Best practices throwing exceptions from properties
- Best way to check for inner exception?
- Best way to handle the error in async node
- Best way to resolve file path too long exception
- Best way to test exceptions with Assert to ensure they will be thrown
- Biggest GWT Pitfalls?
- Binary operator '' cannot be applied to two UIViewAutoresizing operands
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.