Mastering Defensive Programming in Front‑end Development: Prevent, Correct, Guide
This article explains defensive programming for front‑end developers, covering its definition, the three pillars of prevention, correction and direction, common UI and code crisis points, detailed code‑review checklists, CSS defensive rules, and responsive design considerations to build resilient, user‑friendly applications.
PART 1: Understanding Defensive Programming
Defensive programming is a concrete implementation of defensive design that ensures a program remains functional even when used in unforeseen ways, aiming to reduce the impact of Murphy’s law by anticipating incorrect usage and providing prevention, correction, and guidance.
“Defensive programming (Defensive programming) is a concrete embodiment of defensive design, intended to guarantee that unpredictable usage does not damage program functionality. It can be seen as an effort to reduce or eliminate the effects of Murphy’s law.” – Wiki
In front‑end development, defensive means preventing errors that affect user experience and pursuing resilience – the ability of a system to recover from failures while maintaining reliable service. Users may input any value, lose network connectivity, close the page, etc.; the UI must handle these crises gracefully.
Defensive programming manifests in three aspects: prevention, correction, and direction.
A good defensive workflow blocks crises through design and development; when a crisis occurs, correction and direction allow users to continue without abandoning the task.
Prevention, Correction, Direction
Prevention
(details later)
Correction
Broad compatibility (support spaces, semicolons, commas; full‑/half‑width numbers; automatic trimming, etc.).
Clear, constructive error messages and default values so users can keep working.
Real‑time form validation to improve submission success and avoid post‑submission errors.
Direction
Guiding copy that explains the error and the next steps.
Auto‑suggestion components to improve input accuracy.
Fallback or fallback UI that navigates users to a usable branch when an error occurs.
Common UI Defensive Points
Prevent white screen (target < 1 s, ideally <200 ms).
Prevent layout breakage caused by dynamic content.
Prevent extreme content (missing, overly long, repeated characters, unescaped).
Prevent slowness (network, response, rendering, execution).
Prevent freezes or “dead” states.
Prevent consistency issues (inconsistent interactions, icons, components).
Prevent incomplete UI states (missing loading, empty, error, ideal states).
Prevent style pollution (global style leakage).
Prevent chart junk (poorly readable charts).
Prevent dangerous or accidental operations (double‑confirm irreversible actions).
Code Defensive Points
Prevent syntax and logic errors.
Prevent compatibility problems.
Prevent security vulnerabilities.
Prevent unexpected input and interaction.
Prevent extreme or invalid data and API changes.
Prevent code smells and project decay (complexity, duplication, anti‑patterns, dead code).
Prevent inconsistent syntax style.
Prevent merge conflicts.
Prevent redundant code.
Front‑end Code Review Checklist
Type
Checklist Item
General
Are imported packages approved?
Are variable names understandable?
Use const / let for variable declarations.
Validate method parameters and component props.
Avoid hard‑coded values; use constants.
Assign complex conditions to named variables before testing.
Perform necessary type conversions.
Do not introduce unnecessary state.
Check member existence in chain calls or use ?. Optimize nested loops and multi‑level conditionals.
Comment out code with explanations before removal.
Remove unused methods.
Wrap try{...} catch(err){...} with proper error handling.
Handle async requests with three states: loading, empty, error.
Avoid unused API calls in batch requests.
Avoid subscriptions in dva.
Avoid unnecessary global state.
Provide concrete messages for API error codes.
Limit method parameters to ≤5.
Keep file length < 400 lines.
Do not miss internationalization handling.
Eliminate ESLint errors.
Remove console.log statements.
React
Prohibit inline styles.
Prohibit direct DOM manipulation.
Use standard components.
Validate forms with Field component.
Handle form submission processing state.
Show success message after form submission, e.g., Message.success('...').
Replace global variables with useRef.
Wrap loops with useMemo when appropriate.
Wrap callback props with useCallback.
Ensure data‑binding components have loading and empty states.
CSS
Avoid class name collisions.
Prohibit float and absolute layouts; prefer Flexbox/Grid.
Prohibit fixed width/height; use min‑width, max‑width, calc(), relative units.
Avoid directly modifying global styles; use scoped modules or BEM naming.
Avoid !important except for truly immutable styles.
Keep CSS code and files organized per module to prevent accidental changes.
Limit @media rules to module‑specific files.
Remove dead code promptly.
Write complete style definitions; avoid partial overrides.
Scope selectors (e.g., .my‑module .xxx) to prevent conflicts.
Prefer BEM or CSS Modules for naming.
Use precise selectors; avoid overly deep selectors that hurt performance.
UI Defensive Points
Defensive Point
Measure
Prevent white screen
White‑screen monitoring, resource retry, Service Worker fallback, error‑boundary wrappers, compatibility detection, user prompts.
Prevent slowness (network, response, render, execution)
Front‑end performance optimization.
Prevent freezes
Front‑end performance optimization.
Prevent layout breakage
Responsive front‑end development.
Prevent extreme content (missing, overly long, unescaped)
Input validation and sanitization.
Prevent consistency issues
Design guidelines, UI review tools, visual regression testing.
Prevent incomplete UI states
Define full state stack (loading, empty, partial, error, ideal).
Prevent style pollution
Code review.
Prevent chart junk
Use readable chart practices.
Prevent dangerous operations
Double‑confirm irreversible actions with strong prompts.
Responsive Design for B‑end Products
Physical screen resolution does not equal browser window size; designs must adapt to various device resolutions, orientations, and window dimensions. Responsive Web Design (RWD) enables a site to render appropriately across desktops, tablets, and phones, reducing the need for users to zoom or scroll excessively.
CSS Defensive Rules
Defensive Point
Description
Avoid layout components implemented in JavaScript.
JS layout components add unnecessary nesting and lock layout, making CSS control difficult.
Avoid using JavaScript to control layout.
Native flow is smoother; JS layout adds complexity and bugs unless solving a specific compatibility issue.
Avoid outdated layout techniques (float, absolute, table).
Prefer Flexbox or Grid; only use absolute positioning when absolutely necessary.
Avoid fixed width/height.
Fixed dimensions cause overflow; use min‑/max‑ values, calc(), or relative units.
Avoid invasive styling.
Do not affect global styles ( *{...}, :root{...}), avoid modifying common component styles, limit use of !important, and keep style attributes out of HTML.
Avoid CSS code mistakes or omissions.
Separate selectors, keep module‑specific styles together, avoid bulk @media overrides, and delete dead code promptly.
Avoid CSS style conflicts.
Scope selectors (e.g., .my‑module .xxx), use BEM or CSS Modules, and keep selector depth reasonable.
Prevent content misalignment.
Use Flexbox for reliable alignment; avoid unreliable tricks like fixed height or vertical-align.
Prevent content overflow.
Set max‑width / max‑height on images, enable auto‑resize for charts, avoid overflow:hidden on containers unless intentional.
Prevent excessive crowding.
Provide spacing (≈8 px) between horizontally arranged elements; use gap in Flexbox where supported.
Prevent content being hidden.
Avoid negative margins that obscure elements; keep positioning consistent.
Prevent tiny clickable areas.
Enlarge interactive zones to at least 32 × 32 px using pseudo‑elements or padding.
Prevent truncated content.
When using overflow:hidden, ensure content is not cut off; apply ellipsis with
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;.
Prevent improper line breaks.
Use overflow-wrap: break-word and hyphens: auto for long words; keep headings and buttons unwrapped.
Prevent scroll‑chain issues in overlays.
Apply overscroll-behavior: contain; and proper overflow settings.
Prevent image distortion.
Use object-fit: cover; and avoid stretching in Flexbox containers.
Prevent image load failures.
Provide placeholder backgrounds or borders for images.
Prevent missing CSS variables.
Supply fallback values, e.g., font-size: var(--tab-item-text-size-s, 12px);.
Prevent CSS compatibility problems.
Avoid vendor prefixes; rely on preprocessors; test especially on Windows and Safari.
Flexbox defensive patterns.
Define container with
display:flex; flex-wrap:wrap; justify-content:space-between; align-items:center;and set item spacing.
Grid defensive patterns.
Use
grid-template-columns: repeat(auto-fit, minmax(min(200px, 1fr), 1fr));and grid-gap:8px; to avoid fixed widths.
Conclusion
Defensive programming in front‑end development requires a mindset that anticipates user errors, network instability, and platform diversity. By applying systematic prevention, correction, and direction strategies—through UI design, code reviews, CSS rules, and responsive techniques—developers can deliver robust, user‑friendly applications.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
