Defensive Programming Principles and Practices
The article outlines defensive programming concepts, emphasizing input validation, error handling, resource management, isolation techniques, and design considerations such as thread safety, cache strategies, and interface versioning to build robust and resilient software systems.
Defensive programming asserts that subroutines should not be broken by erroneous input, even when that input originates from other subroutines.
The core idea is to acknowledge that all programs have bugs and need modification, and that smart developers should write code with this reality in mind.
Defensive programming cases include:
1. Protecting programs from illegal input data – respond by validating parameters (checking external data values, ranges, string lengths, SQL‑injection patterns), inspecting all input arguments, deciding how to handle bad data, avoiding large Redis keys/values, handling duplicate requests with idempotency or distributed locks, and preventing over‑privileged interfaces that expose sensitive data.
2. Assertions
3. Error‑handling techniques – return neutral values, substitute the next correct data, reuse previous data, choose the nearest legal value, log information, return an error code, invoke an error‑handling routine or object, display error messages, handle errors locally in a safe way, or shut down the program.
4. Exceptions
5. Isolation – use thread‑pool isolation, circuit breakers, degradation, rate limiting, feature flags, and split services and their dependent resources such as databases or Redis.
6. Resource exhaustion and memory leaks leading to OOM – avoid unlimited resource creation, reuse resources, employ bounded containers, and paginate queries instead of full‑table scans.
7. Thread safety
8. Interface version compatibility
9. Cache design – guard against cache breakdown, design expiration to avoid hot spots, and consider storage capacity.
10. Database read/write splitting – account for master‑slave latency and resulting data‑consistency issues.
11. Interface timeout retries – ensure idempotency and data consistency.
References: "Code Complete 2" (Chinese edition), articles on defensive and offensive programming, enterprise craftsmanship, and related blog posts.
Cognitive Technology Team
Cognitive Technology Team regularly delivers the latest IT news, original content, programming tutorials and experience sharing, with daily perks awaiting you.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.