mewmew/swebp icon
public
Published on 5/19/2025
Software engineering best practices

A rulebook for software engineering best practices.

Rules

aiCodingRulebook: rules: - id: AdhereToSpecifications description: "Code must directly implement provided specifications without deviation or assumption. The AI must act as a precise executor of clearly defined tasks." directives: - "Verify every functional and non-functional requirement from the input specification is explicitly addressed in the generated code." - "Do not infer requirements, features, or behaviors not explicitly stated. If ambiguity or missing information is detected in the specification, either halt and report the ambiguity (if interactive) or clearly document the assumption made and why, then proceed with the most conservative interpretation." - "Cross-reference generated code sections (e.g., via comments or metadata if supported) back to the specific requirement ID they fulfill." - "If a requirement cannot be met due to conflicting constraints or technical impossibility, report this clearly instead of generating non-compliant code."

- id: StructuredDesignPrinciples
  description: "Generated code must embody established software design and architectural principles to ensure robustness, maintainability, and clarity."
  directives:
    - "Prioritize modularity: Decompose problems into the smallest logical, cohesive, and independently testable units (functions, classes, methods, modules). Each unit should have a single, well-defined responsibility."
    - "Enforce Separation of Concerns (SoC): Ensure that distinct aspects of the software (e.g., UI, business logic, data access) are handled by separate, loosely coupled modules."
    - "Apply DRY (Don't Repeat Yourself): Scrutinize generated code for any redundant logic or data representation. Abstract repeated segments into reusable functions, methods, constants, or classes."
    - "Implement KISS (Keep It Simple, Stupid): Opt for the simplest, most straightforward solution that fully meets the requirements. Avoid unnecessary complexity, layers of abstraction, or overly intricate algorithms."
    - "Follow YAGNI (You Ain't Gonna Need It): Generate code exclusively for features and functionalities explicitly requested in the current specifications. Do not add features for anticipated future needs."
    - "Ensure clear data flow and minimize global state. Prefer passing data explicitly as parameters."

- id: RigorousAutomatedTesting
  description: "Generated code must be inherently testable, and where specified, accompanied by comprehensive automated tests."
  directives:
    - "Produce code with clear inputs and outputs, minimal side effects (for functions), and well-defined interfaces to facilitate unit testing."
    - "If generation of tests is specified: Create unit tests for all public functions and methods. For object-oriented code, test class behaviors and interactions."
    - "Unit tests must cover: a) valid inputs demonstrating normal operation, b) documented edge cases (e.g., min/max values, empty inputs), c) common error conditions and invalid inputs, verifying appropriate error handling."
    - "If employing a Test-Driven Development (TDD) or Behavior-Driven Development (BDD) approach (as per specification): Generate tests before or concurrently with the functional code. All functional code must directly satisfy one or more test assertions."
    - "Strive for high test coverage of the generated logic."

- id: AdhereToCodingStandards
  description: "Generated code must strictly and consistently follow specified coding standards, style guides, and conventions for the target language and project."
  directives:
    - "Apply the designated style guide (e.g., PEP 8 for Python, Google Style Guide for Java/C++, Prettier for JavaScript) for all aspects of code formatting: indentation, line length, spacing, brace style, import organization, etc."
    - "Use clear, descriptive, and consistent naming conventions for variables, functions, classes, methods, constants, and modules. Names should clearly indicate the entity's purpose or content."
    - "Avoid overly terse, cryptic, or misleading names. Follow language-specific conventions (e.g., camelCase, snake_case)."
    - "Ensure code structure (e.g., file organization, class layout) follows project or language best practices."

- id: ComprehensiveCodeDocumentation
  description: "Generated code must be thoroughly documented with clear comments and, where applicable, formal API documentation to explain its purpose, usage, and design."
  directives:
    - "Add inline comments to explain non-obvious logic, complex algorithms, critical assumptions made, or workarounds for specific issues."
    - "Generate API documentation (e.g., docstrings in Python, Javadoc in Java, XML-doc in C#) for all public functions, classes, methods, and modules. This documentation must detail: its overall purpose, each parameter (name, type, description, optional/required), return values (type, description), and any exceptions it may raise."
    - "Ensure all comments and documentation are accurate, up-to-date with the code, and written in clear, grammatically correct language."
    - "For complex modules or classes, provide a block comment at the beginning summarizing its role and high-level design."

- id: SystematicErrorHandling
  description: "Generated code must include robust and systematic error handling mechanisms and be resilient to invalid inputs, unexpected states, or external system failures."
  directives:
    - "Identify potential points of failure (e.g., I/O operations, network requests, data conversions, invalid user inputs) and implement specific error handling for each (e.g., try-catch blocks, error codes, Option/Result types)."
    - "Validate inputs to all public functions/methods and critical internal functions for correctness (type, range, format) before processing."
    - "Provide informative and actionable error messages that can aid in debugging and clearly indicate the nature of the problem."
    - "Avoid catching overly broad exceptions (e.g., `catch (Exception e)`) unless the intent is to log and re-throw, or perform a very generic cleanup. Catch specific exception types."
    - "Ensure that resources (e.g., file handles, database connections, memory allocations) are properly managed and reliably released, even in the event of errors (e.g., using `finally` blocks or try-with-resources constructs)."
    - "Implement strategies for graceful degradation if parts of the system fail."

- id: PrioritizeReadabilityAndMaintainability
  description: "Code generation must prioritize clarity, readability, and long-term maintainability by human developers over premature or overly complex micro-optimizations."
  directives:
    - "Generate code that is logically structured, with a clear flow of control, and is easy for a human developer to follow and understand."
    - "Break down complex operations into smaller, well-named, understandable steps or helper functions."
    - "Avoid overly clever, obscure, or idiomatic language features if simpler, more widely understood alternatives exist and meet performance requirements."
    - "Apply performance optimizations only when explicitly specified by requirements or after profiling has identified a genuine bottleneck. Any such optimization must be clearly documented with its rationale and impact."
    - "Use whitespace effectively to improve readability."

- id: IterativeRefinementCapability
  description: "The code generation process should be designed to support iterative refinement based on feedback, test results, or evolving specifications."
  directives:
    - "If validation errors, test failures, static analysis warnings, or explicit human feedback are provided for previously generated code, re-evaluate and regenerate or modify the code to address all identified issues comprehensively."
    - "Maintain a context of previous generation attempts and feedback (if the platform supports it) to inform subsequent refinements and avoid repeating mistakes or reintroducing resolved issues."
    - "Log changes made during refinement cycles, ideally referencing the specific feedback or test failure that prompted the change."
    - "Be prepared to decompose and regenerate specific sections of code rather than entire modules if feedback is localized."

- id: SecurityConsciousCodingDefaults
  description: "Generated code must adhere to fundamental secure coding principles by default to minimize common vulnerabilities."
  directives:
    - "Avoid common security vulnerabilities applicable to the language and domain (e.g., SQL injection, Cross-Site Scripting (XSS), command injection, insecure direct object references, XML External Entity (XXE) injection, insecure deserialization, hardcoded secrets/credentials)."
    - "Sanitize and validate ALL external inputs from any untrusted source (e.g., user input, network data, file contents) before use."
    - "Use parameterized queries or prepared statements for all database interactions; never construct SQL queries by string concatenation with user input."
    - "Follow the principle of least privilege: ensure code operates with the minimum permissions necessary."
    - "Employ standard, well-vetted cryptographic libraries for any security-sensitive operations (e.g., hashing, encryption); do not attempt to implement custom cryptographic algorithms."
    - "Encode output data appropriately to prevent injection attacks when rendering it in different contexts (e.g., HTML, JavaScript, SQL)."

- id: JustifyCodeConstructsAndDecisions
  description: "Generated code should, where feasible and specified, include traceability or justifications for non-obvious design choices or implementations."
  directives:
    - "If the input specification format supports it, include metadata or structured comments that link specific code blocks, functions, or classes back to the particular requirement ID or design document section they are intended to implement."
    - "For complex algorithms, non-trivial design choices, or the use of less common patterns, add a brief comment explaining the rationale behind the chosen approach, especially if alternative solutions were considered and rejected."
    - "If an assumption was made due to ambiguous or incomplete requirements (and reported as per `AdhereToSpecifications`), clearly document this assumption and its impact directly within the affected code or its associated documentation."