Defensive programming is an approach to improve software and source code, in terms of:
- General quality – reducing the number of software bugs and problems.
- Making the source code comprehensible – the source code should be readable and understandable so it is approved in a code audit.
- Making the software behave in a predictable manner despite unexpected inputs or user actions.
Clean Code
- Easy to read
- Clear intent
- Simple
- Minimal
- Thoughtful
Defensive Coding
- Clean Code
- Testable Code + Unit Tests
- Validation + Exception Handling
Clean, Testable, Predictable Methods
-
Clear Purpose
-
Good Name
-
Focused Code
-
Short Length
-
Automated Code Test
-
Guard Clauses
-
Minimize Number of Parameters
-
Consistent Parameter Ordering
Automated Code Tests
-
Structured
-
Self-documented
-
Automated
-
Repeatable
-
TARDS (Time and Relative Dimension in Space)
-
AAA for Testing
- Arrange
- Act
- Asser
Key Considerations
- Best Practices
- Clarity of Intent
- Predictability
Use 'as' for casting instead of blind cast