{"id":10729,"library":"defensive-programming-framework","title":"Defensive Programming Framework","description":"The `defensive-programming-framework` is a TypeScript and JavaScript utility library designed to streamline and standardize input parameter validation, thereby fostering more robust code. Currently at version 1.0.4, it provides a collection of concise helper functions that abstract away common validation checks, reducing the boilerplate associated with manual `if (...) { throw new ArgumentError(...) }` statements. Its primary differentiator is the focus on either immediate termination via `ArgumentError` on failure (unconditional validation) or optional input correction, making validation logic more readable and maintainable. The framework aims to reduce the time and effort typically required for comprehensive input validation, encouraging developers to implement these crucial checks without inflating function bodies with repetitive error-checking code.","status":"active","version":"1.0.4","language":"javascript","source_language":"en","source_url":"https://github.com/aljazsim/defensive-programming-framework-for-typescript","tags":["javascript","defensive programming","validation","verification","checking","parameter","input","typescript"],"install":[{"cmd":"npm install defensive-programming-framework","lang":"bash","label":"npm"},{"cmd":"yarn add defensive-programming-framework","lang":"bash","label":"yarn"},{"cmd":"pnpm add defensive-programming-framework","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Primary utility for unconditional 'cannot be null' checks. Framework is ESM-first, use named imports.","wrong":"const cannotBeNull = require('defensive-programming-framework');","symbol":"cannotBeNull","correct":"import { cannotBeNull } from 'defensive-programming-framework';"},{"note":"Typical usage is via named imports for specific validation functions.","wrong":"import mustBeGreaterThanOrEqualTo from 'defensive-programming-framework';","symbol":"mustBeGreaterThanOrEqualTo","correct":"import { mustBeGreaterThanOrEqualTo } from 'defensive-programming-framework';"},{"note":"Used for optional/corrective validation, where input can be modified instead of throwing an error.","symbol":"whenIsNull","correct":"import { whenIsNull } from 'defensive-programming-framework';"},{"note":"The custom error class thrown by unconditional validation functions. Must be imported to catch specifically.","wrong":"new ArgumentError('message')","symbol":"ArgumentError","correct":"import { ArgumentError } from 'defensive-programming-framework';"}],"quickstart":{"code":"import {\n  cannotBeNull,\n  mustBeGreaterThanOrEqualTo,\n  whenIsNull,\n  whenIsLessThan,\n  ArgumentError\n} from 'defensive-programming-framework';\n\n/**\n * Example function demonstrating defensive programming with the framework.\n * Validates and potentially corrects input parameters.\n */\nexport function write(buffer: number[], startIndex: number, data: number[]): void {\n  // Unconditional validation - throws ArgumentError on failure\n  cannotBeNull(buffer); // Throws if buffer is null\n  cannotBeNull(data);   // Throws if data is null\n\n  // Corrective validation - attempts to fix input, returns corrected value\n  // If startIndex is less than 0, it's corrected to 0.\n  startIndex = whenIsLessThan(startIndex, 0, 0);\n  // If data is null, it's corrected to an empty array.\n  data = whenIsNull(data, []);\n\n  // Mixed validation - ensuring corrected values meet further conditions\n  mustBeGreaterThanOrEqualTo(startIndex, 0); // Re-validate startIndex (now guaranteed >= 0 if corrected)\n  \n  // Custom conditional check (can be wrapped in a framework function if frequently used)\n  if (data.length >= buffer.length - startIndex) {\n    throw new ArgumentError(`Length of data cannot be greater than remaining buffer space (${buffer.length - startIndex}).`);\n  }\n\n  console.log('Validation passed. Proceeding with actual write operation...');\n  // Actual execution code would go here\n  // For demonstration, let's just log the validated inputs\n  console.log('Buffer:', buffer);\n  console.log('StartIndex:', startIndex);\n  console.log('Data:', data);\n}\n\n// Example usage:\ntry {\n  console.log('\\n--- Valid Case ---');\n  write([1, 2, 3, 4, 5], 1, [10, 20]); // Valid inputs\n\n  console.log('\\n--- Corrective Case ---');\n  write([1, 2, 3, 4, 5], -5, null);    // startIndex corrected to 0, data corrected to []\n\n  console.log('\\n--- Error Case ---');\n  write([1, 2], 0, [10, 20, 30]);      // Data length too large for buffer\n} catch (e) {\n  if (e instanceof ArgumentError) {\n    console.error('Validation Error (caught):', e.message);\n  } else {\n    console.error('Unexpected Error (caught):', e);\n  }\n}","lang":"typescript","description":"Demonstrates both unconditional (error-throwing) and corrective (input-modifying) validation using core framework functions like `cannotBeNull`, `whenIsLessThan`, `whenIsNull`, and `ArgumentError`."},"warnings":[{"fix":"Ensure all calls to unconditional validation functions are either preceded by checks that guarantee success, or are wrapped in `try...catch` blocks to handle the `ArgumentError` gracefully.","message":"The framework's 'unconditional' validation functions (e.g., `cannotBeNull`, `mustBeEqualTo`) throw an `ArgumentError` on failure. This is an assertive pattern that halts execution, which might not be suitable for all validation contexts, especially those requiring soft failures or complex UI feedback.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always include `import { ArgumentError } from 'defensive-programming-framework';` and use `if (e instanceof ArgumentError)` in your catch blocks for specific error handling.","message":"To specifically catch and handle errors thrown by the framework's validation, you must import and use `ArgumentError` with `instanceof`. Generic `catch (e)` blocks will not allow distinguishing framework errors from other exceptions.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Combine framework functions with custom `if` statements for intricate validation scenarios, or encapsulate custom logic into reusable helper functions.","message":"While the framework simplifies common checks, it does not inherently replace all custom validation logic. For complex, multi-variable conditions or custom error messages not covered by existing helpers, developers still need to implement explicit checks.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Add `import { ArgumentError } from 'defensive-programming-framework';` to your file.","cause":"The `ArgumentError` class was used without being imported from the package.","error":"ReferenceError: ArgumentError is not defined"},{"fix":"Ensure you have `import { cannotBeNull } from 'defensive-programming-framework';` (or the specific function) at the top of your file.","cause":"A validation utility function (e.g., `cannotBeNull`, `mustBeEqualTo`) was called without being imported.","error":"TypeError: cannotBeNull is not a function"},{"fix":"Wrap the code that calls the validation function in a `try...catch` block. For asynchronous operations, ensure the `catch` block is properly chained or awaited.","cause":"An unconditional validation function threw an `ArgumentError` which was not caught, typically in an asynchronous context or at the top level of execution.","error":"UnhandledPromiseRejectionWarning: ArgumentError: Value cannot be null."}],"ecosystem":"npm"}