{"id":23,"date":"2024-08-24T11:10:12","date_gmt":"2024-08-24T10:10:12","guid":{"rendered":"https:\/\/contentlabstudy.com\/soft\/?p=23"},"modified":"2026-09-24T21:15:28","modified_gmt":"2026-09-24T20:15:28","slug":"defensive-programming","status":"publish","type":"post","link":"https:\/\/contentlabstudy.com\/soft\/defensive-programming\/","title":{"rendered":"Defensive Programming"},"content":{"rendered":"<p><strong>Defensive programming<\/strong> is writing code that assumes inputs, clocks, disks, and other teams will lie. It is not \u201cnull-check everything\u201d and not \u201cnever throw.\u201d It is making implicit contracts explicit and failing in a way the caller can handle.<\/p>\n<h2>Trust boundaries<\/h2>\n<p>Draw the line: HTTP body, queue payload, file, environment, clock, \u201cthe other microservice.\u201d Inside the line, prefer types that cannot represent illegal states. At the line, parse \u2014 do not cast.<\/p>\n<pre><code>\/\/ untrusted\nvar raw = request.Query[\"page\"];\nif (!int.TryParse(raw, out var page) || page &lt; 1 || page &gt; 1000)\n    return Results.BadRequest();\n<\/code><\/pre>\n<p>Do not sprinkle <code>int.Parse<\/code> on query strings and hope.<\/p>\n<h2>Make illegal states unrepresentable<\/h2>\n<p>Replace boolean flags that contradict each other with a discriminated union or a small enum. An <code>Order<\/code> that is both <code>Cancelled<\/code> and <code>Shipped<\/code> is a bug factory. In C#, records + required members + private constructors beat public setters on every field.<\/p>\n<pre><code>sealed class FlaggedOrder\n{\n    public bool IsShipped { get; set; }\n    public bool IsCancelled { get; set; } \/\/ both can be true\n}\n\nenum OrderStatus { Placed, Shipped, Cancelled }\n\nsealed record StatusOrder(OrderStatus Status);<\/code><\/pre>\n<p><code>FlaggedOrder<\/code> can be shipped and cancelled at once. <code>StatusOrder<\/code> cannot.<\/p>\n<h2>Fail closed vs fail open<\/h2>\n<p>Authorization, payments, and privacy: <strong>fail closed<\/strong> (deny if unsure). Observability and optional recommendations: fail open with a metric. Defaulting \u201callow\u201d on a missing role claim is an incident.<\/p>\n<h2>Assertions, not business control flow<\/h2>\n<p>Use assertions \/ <code>Debug.Assert<\/code> \/ \u201cthis is a programmer error\u201d exceptions for broken invariants (null repository in a composition root). Use domain results or HTTP 4xx for user-fixable mistakes. Catching <code>Exception<\/code> around a whole request and returning 200 hides outages.<\/p>\n<h2>Timeouts, cancellation, idempotency<\/h2>\n<p>Pass <code>CancellationToken<\/code>. Honor it in I\/O. Treat client disconnect as cancel, not as \u201ckeep writing the report.\u201d For handlers that may run twice (at-least-once queues, user double-submit), store an idempotency key. See <a href=\"\/soft\/reliability-design-patterns\/\">reliability patterns<\/a>.<\/p>\n<h2>What breaks it<\/h2>\n<p>The catch turns a downed gateway into HTTP 200. Delete it: the fault stays a 500. Return a 4xx only for input the caller can fix.<\/p>\n<pre><code>static IResult HideTheFault()\n{\n    try\n    {\n        throw new InvalidOperationException(\"gateway down\");\n    }\n    catch (Exception)\n    {\n        return Results.Ok();\n    }\n}<\/code><\/pre>\n<h2>Pitfalls<\/h2>\n<ul>\n<li>Swallowing exceptions to \u201ckeep the app up.\u201d<\/li>\n<li>Logging tokens, PAN, or session cookies \u201cfor debug.\u201d<\/li>\n<li>Defensive copies nowhere, then mutating a cached DTO.<\/li>\n<li>Validating only on the client.<\/li>\n<\/ul>\n<p>Related: <a href=\"\/soft\/owasp-top-ten\/\">OWASP Top Ten<\/a>, <a href=\"\/soft\/sql-for-business-logic\/\">SQL for Business Logic<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Defensive programming is writing code that assumes inputs, clocks, disks, and other teams will lie. It is not \u201cnull-check everything\u201d [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[3],"tags":[],"class_list":["post-23","post","type-post","status-publish","format-standard","hentry","category-software-development"],"_links":{"self":[{"href":"https:\/\/contentlabstudy.com\/soft\/wp-json\/wp\/v2\/posts\/23","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/contentlabstudy.com\/soft\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/contentlabstudy.com\/soft\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/contentlabstudy.com\/soft\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/contentlabstudy.com\/soft\/wp-json\/wp\/v2\/comments?post=23"}],"version-history":[{"count":7,"href":"https:\/\/contentlabstudy.com\/soft\/wp-json\/wp\/v2\/posts\/23\/revisions"}],"predecessor-version":[{"id":3224,"href":"https:\/\/contentlabstudy.com\/soft\/wp-json\/wp\/v2\/posts\/23\/revisions\/3224"}],"wp:attachment":[{"href":"https:\/\/contentlabstudy.com\/soft\/wp-json\/wp\/v2\/media?parent=23"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/contentlabstudy.com\/soft\/wp-json\/wp\/v2\/categories?post=23"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/contentlabstudy.com\/soft\/wp-json\/wp\/v2\/tags?post=23"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}