# Documentation & Knowledge

Reference material, curated lists and learning resources — mostly writing and structure guidance.

61 instructions from 6 repositories. Last updated 2026-05-08.

---

## Documentation clarity rules

<!-- source: freeCodeCamp/freeCodeCamp | topic: Documentation | language: Markdown | updated: 2026-05-08 -->

When writing technical curriculum/docs, ensure the content is (a) accurate, (b) unambiguous about what learners must do and what the expected output/input is, and (c) consistent in formatting and tone.

Apply these rules:
- Fix correctness issues before merging: verify command/API names and options; avoid typos (e.g., `express.urlencoded`).
- Separate responsibilities:
  - `--description` teaches the concept/skill.
  - `--explanation` justifies the correct answer (don’t blend explanation/translation into description).
- Avoid redundant instructions (e.g., remove “There’s just one correct answer.” from multiple-choice tasks).
- Use house-style for inline code and typography:
  - Wrap code/terms in backticks (and use consistent straight quotes/backticks, not mixed typographic variants).
  - Put English punctuation outside closing quotes.
- Keep learner-facing tone neutral: avoid “we” when addressing learners.
- Make required user output expectations explicit with examples when the prompt depends on a specific shape (e.g., show the expected prop/type signature or object structure).
- Ensure lists/structure follow the intended format (e.g., user stories should be an ordered list) and that input/output expectations are clear from the text.

Example pattern (description vs explanation):
```md
# --description--
To run the program, use:
```bash
python main.py
```

# --explanation--
The command must be run from the folder that contains `main.py`.
```

---

## Consistent Snippet Style

<!-- source: freeCodeCamp/freeCodeCamp | topic: Code Style | language: Markdown | updated: 2026-05-08 -->

All code snippets, hints, seed code, and automated checks must follow a single, consistent formatting and style contract—especially around quote usage and basic JS/TS syntax.

Apply these rules:
- **Formatting:** use the team’s standard indentation (e.g., 2 spaces) and include semicolons consistently.
- **No broken snippets:** seed code examples must compile/parse; avoid syntax errors and duplicate declarations.
- **Quote-robust tests/hints:** when matching user code, support **both** single and double quotes and (when relevant) ensure the same quote type is used via backreferences.
- **Pattern consistency:** hints should prefer the same DOM/API patterns the seed uses (to avoid ambiguity), unless there’s an explicit reason to allow alternatives.

Example (quote-robust hint regex):
```js
// Matches: document.getElementById('income') or document.getElementById("income")
assert.match(code, /document\.getElementById\(\s*(['"])income\1\s*\)/);
```

Example (style-correct TS):
```ts
function f(): void {
  const x = 1;
  console.log(x);
}
```

Example (avoid duplicate seed declarations):
```ts
const cardDisplay = document.querySelector<HTMLElement>("#current-card")!; 
// (don’t redeclare cardDisplay again)
```

---

## Express error handling

<!-- source: freeCodeCamp/freeCodeCamp | topic: Error Handling | language: Markdown | updated: 2026-05-08 -->

For Express apps, standardize error handling as follows:

- Define error-handling middleware with the correct signature: `(err, req, res, next)`.
- Register it last in the middleware chain (after routes). If you add a 404 handler, place it after routes but before the error handler.
- For async route handlers (especially in Express 4), never rely on Express to catch thrown/rejected async errors—propagate them to the error middleware using `next(err)` via `try/catch` or an `asyncHandler` helper.
- Log full error details server-side, but return user-friendly messages to clients (avoid sending stack traces in production).

Example (safe ordering + async propagation):

```js
const express = require('express');
const app = express();

// Routes
app.get('/', (req, res) => {
  throw new Error('Something went wrong');
});

// 404 handler (after routes, before error handler)
app.use((req, res) => {
  res.status(404).send('Sorry, that route does not exist.');
});

// Async error helper (optional)
function asyncHandler(fn) {
  return (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next);
}

app.get('/user', asyncHandler(async (req, res) => {
  const user = await getUserFromDatabase();
  res.send(user);
}));

// Error-handling middleware (LAST)
app.use((err, req, res, next) => {
  console.error(err); // log details internally
  res.status(500).send('Internal Server Error'); // user-friendly response
});
```

Apply this checklist consistently when adding new routes or refactoring middleware order to prevent unhandled promise rejections, ensure consistent HTTP responses, and avoid leaking sensitive error details.

---

## Middleware and Status Semantics

<!-- source: freeCodeCamp/freeCodeCamp | topic: API | language: Markdown | updated: 2026-05-08 -->

When building API endpoints with Express, make request lifecycle control-flow and response semantics explicit and consistent:

- Middleware chaining: only call `next()` when you intend to continue to the next middleware/handler; if you don’t call `next()`, the request-response cycle will stop.
- Ordering: rely on the fact middleware executes in the order it’s added; mount router modules intentionally.
- Response outcomes: in each terminal handler, return an HTTP status code that matches the outcome (e.g., `400` for bad requests, `200` for success, `500` for server errors) and use an appropriate body format (string vs JSON).

Example:
```js
const express = require('express');
const app = express();

// Global middleware (runs in order)
app.use((req, res, next) => {
  console.log(req.method, req.url);
  next(); // continue the lifecycle
});

const api = express.Router();
api.use('/v1', (req, res, next) => {
  // router-level middleware
  next();
});

api.get('/v1/resource', (req, res) => {
  // terminal handler: choose status code + body that match the outcome
  return res.status(200).json({ ok: true });
});

api.post('/v1/resource', express.json(), (req, res) => {
  if (!req.body || !req.body.name) {
    return res.status(400).send('Bad Request');
  }
  return res.status(201).json({ created: true });
});

app.use(api);
app.listen(3000);
```

Use this checklist in reviews:
1) Does every middleware either call `next()` or send a response (intentionally terminating)?
2) Are middleware/routers mounted in the intended order/module boundaries?
3) Do your route handlers return status codes and response bodies that accurately represent success/client error/server error?

---

## Middleware ordering and chaining

<!-- source: freeCodeCamp/freeCodeCamp | topic: Networking | language: Markdown | updated: 2026-05-08 -->

When using Express, treat middleware registration as an HTTP request-processing pipeline: middleware executes in the order you add it, and the chain advances only if your middleware calls `next()`.

Apply this standard:
- Use the canonical middleware signature in code/docs: `(req, res, next)`.
- Register middleware with `app.use(...)` (and any static middleware) in the exact order you need.
- Call `next()` whenever the request should continue to later middleware/route handlers; if you don’t call it, the request-response cycle stops.
- Stack built-in and third-party middleware intentionally; later middleware can depend on earlier changes to `req`/`res`.

Example:
```js
const express = require('express')
const cors = require('cors')
const morgan = require('morgan')
const app = express()

// 1) Parse/prepare request (built-in)
app.use(express.json())

// 2) Middleware behavior depends on order (third-party)
app.use(cors())
app.use(morgan('tiny'))

// 3) Intercept/transform request, then continue
app.use((req, res, next) => {
  req.requestId = req.header('x-request-id')
  next() // must be called to reach the next middleware/route
})

// 4) Serve static assets via middleware (register intentionally)
app.use(express.static('public'))

app.get('/', (req, res) => res.send('Hello'))

app.listen(3000)
```

Outcome: predictable HTTP behavior, fewer “why didn’t my route run?” issues, and middleware effects (auth, logging, parsing, static serving) that are consistent across the app.

---

## Docstring Standards

<!-- source: TheAlgorithms/Python | topic: Documentation | language: Python | updated: 2026-05-05 -->

Apply a single documentation rule set across the codebase:

- **Module/file docstring:** Each file should have a clear module-level docstring **before any imports**.
- **Docstring completeness:** Docstrings must explain *behavior*, key **assumptions** (inputs/constraints), important **units**, and any **approximation** or dependency requirements needed to use the code.
- **No type duplication:** Do **not** repeat parameter/return data types in the docstring when they are already present in the function signature (let the type hints be the source of truth).
- **Consistent style/wording:** Follow the repo’s chosen docstring convention (e.g., Sphinx-style) and ensure wording starts appropriately (for lint rules like “docstring starts with this”).
- **Doctests stay with docs:** If docstrings contain doctests that act as unit tests, keep them; add doctests to validate behavior for new functions.
- **Keep comments accurate/redundant-free:** Don’t add comments that contradict docstring intent; avoid duplicating what a docstring already explains.

Example (illustrates the “no type duplication” + clear behavior):
```py
def time_period_of_satellite(mass: float, radius: float, height: float) -> float:
    """Calculate the orbital period of a satellite.

    Uses T = 2π * sqrt((R + h)^3 / (G * M)).

    Units: mass in kg, radius/height in meters.
    """
    ...
```

Operationally: during review, enforce these as checklist items for every new/changed file and function/method docstring.

---

## Validate Inputs Explicitly

<!-- source: TheAlgorithms/Python | topic: Error Handling | language: Python | updated: 2026-05-05 -->

Enforce each function’s documented input contract with early, explicit checks; raise specific exceptions with accurate messages (avoid asserts, silent fallbacks/defaults, and misleading error paths after normalization). Keep try/except blocks as narrow as possible—only around the operations that can fail.

Guideline checklist:
- Align runtime validation with docstrings and examples (if doc says “non-negative s”, reject s_value < 0).
- Validate relationships/ranges using a single correct predicate (e.g., reject values where a computed sine is not within [-1, 1]).
- Prefer ValueError/TypeError over assert; never rely on assertions for user-facing correctness.
- Do not silently change behavior for invalid configuration (raise ValueError instead of defaulting mode).
- After normalization (strip sign/whitespace), ensure the error message still matches the actual failing condition.
- For CLI/I/O parsing, limit try/except to the conversion line(s); don’t wrap the whole program.

Example pattern:
```py
import math

def calculate_refraction_angle(n1: float, n2: float, incident_angle_degrees: float) -> float:
    # precondition: physical/numerical domain
    if n1 <= 0 or n2 <= 0:
        raise ValueError("Refractive indices must be positive")

    theta1 = math.radians(incident_angle_degrees)
    refraction_sine = (n1 / n2) * math.sin(theta1)

    # physical validity in one place; message stays truthful
    if not -1.0 <= refraction_sine <= 1.0:
        raise ValueError("Total Internal Reflection or invalid physical inputs")

    return math.degrees(math.asin(refraction_sine))
```

Apply the same approach across data structures and educational utilities: validate configuration (raise on invalid mode), validate parameter types/relationships, and make failure modes deterministic and easy to understand.

---

## Algorithm Correctness Standards

<!-- source: TheAlgorithms/Python | topic: Algorithms | language: Python | updated: 2026-05-05 -->

When implementing algorithms, enforce correctness and reliability by following this checklist:

1) Validate stated preconditions (and document them)
- If the algorithm only works for certain input ranges/shapes (e.g., cyclic sort requires values in 1..n with no duplicates), explicitly check those conditions and fail fast with a clear error.

2) Handle numerical/semantic edge cases explicitly
- For floating-point boundary conditions, use `math.isclose()` (and/or symmetric checks) instead of direct comparisons.
- For floating-point pivot/zero checks, use a tolerance rather than `== 0.0`.

3) Ensure algorithm invariants are implemented (especially graph/search)
- If the correctness relies on traversal order (e.g., DFS post-order), apply required transformations (`reverse()`) and add a brief comment explaining why.

4) Avoid unnecessary extra passes
- Prefer single-pass grouping/processing over multiple full iterations when the same data can be grouped in one traversal.

Example pattern (single-pass grouping + clear precondition validation):
```python
from collections import defaultdict

def group_by_priority(items: list[dict]) -> dict[str, list[dict]]:
    grouped: dict[str, list[dict]] = defaultdict(list)
    for item in items:
        grouped[item["priority"]].append(item)
    return dict(grouped)

def cyclic_sort_guard(nums: list[int]) -> None:
    n = len(nums)
    if any(x < 1 or x > n for x in nums):
        raise ValueError("Cyclic sort requires all values in the range [1, len(nums)]")
    if len(set(nums)) != n:
        raise ValueError("Cyclic sort requires no duplicates")
```

Adopting this standard will reduce subtle correctness bugs (wrong logic/invariants), runtime failures (invalid inputs/infinite loops), and precision-related issues, while also improving efficiency for larger inputs.

---

## Consistent Identifier Naming

<!-- source: freeCodeCamp/freeCodeCamp | topic: Naming Conventions | language: Markdown | updated: 2026-05-04 -->

When updating curriculum challenges or UI code, ensure all identifiers are spelled, cased, and named consistently across: the prompt, hints, and what tests/DOM queries expect. Also use framework-correct attribute names (e.g., JSX `className`) and semantic, descriptive labels for user-facing accessibility (e.g., informative `alt` text).

**Checklist**
- **Exact name matching:** If instructions mention `utilitiesNumberInputs`, but tests assert `utilitiesInputs`, make the instruction/hint match the actual variable name used/required.
- **Correct JSX/DOM attribute names:** In JSX/TSX use `className` (not `class`).
- **Descriptive user-visible naming:** For images, don’t use vague alt text like `"Player"`; name what’s actually shown.
- **Casing and function naming:** Keep function names consistent with the expected casing (e.g., `getLongestSubstring`).
- **Signature clarity:** When type annotations are required by tests, make the function signature match the expected parameter name and type annotation (and don’t introduce distractor typos like `renderMotorCycleCard` vs `renderMotorcycleCard`).

**Example**
```js
// JSX/TSX: use className
return <img src=".../pele.jpg" alt="Pelé headshot" className="card-image" />;

// Spec/tests: ensure variable names match exactly
const utilitiesInputs = document.querySelectorAll("#utilities input[type='number']");
```

---

## Automate All Behavior Tests

<!-- source: TheAlgorithms/Python | topic: Testing | language: Python | updated: 2026-05-02 -->

For every algorithmic change (and every public function/class), require automated tests that lock in both correctness and failure modes.

Minimum standard:
- Prefer assertions/doctests over “print and eyeball.” (Printing-only checks are not sufficient.)
- Add doctests or pytest cases for: 
  - happy path(s)
  - edge cases (empty input, boundaries, negative values, single element)
  - invalid inputs / rejected preconditions (at least one case that should fail or return a sentinel)
- Don’t weaken confidence with tests that all assert the same output for different inputs—add cases that meaningfully differ.
- Keep existing tests; don’t remove doctests “just because.”
- Ensure doctests actually execute in the module (e.g., call `doctest.testmod()` in `__main__`).
- Avoid nested helper functions when you rely on doctest coverage inside their docstrings; keep testable code at module level.

Example pattern (doctest with edge + failure):
```python
def interpolation_search(sorted_collection: list[int], item: int) -> int | None:
    """
    >>> interpolation_search([1, 2, 3, 4, 5], 2)
    1
    >>> interpolation_search([1, 2, 3, 4, 5], 6) is None
    True
    >>> interpolation_search([], 1) is None
    True
    """
    ...

if __name__ == "__main__":
    import doctest
    doctest.testmod()
```

This standard directly prevents regressions (new validation rules, edge-case fixes, and invariants) and makes behavior verification repeatable and reviewable.

---

## Performance-Sensitive Efficiency

<!-- source: TheAlgorithms/Python | topic: Performance Optimization | language: Python | updated: 2026-05-02 -->

When optimizing, watch for *hidden* inefficiencies: avoid O(n) per-step operations, don’t duplicate expensive work, and don’t eagerly materialize/convert data unless needed.

Apply these checks:
- **Choose linear-time operations for hot loops**: don’t repeatedly shift lists (e.g., `insert(0, ...)`). Prefer build-then-postprocess (append + reverse) when ordering allows.
- **Compute once per candidate/path**: avoid patterns that re-run the same expensive computation in both an `if` and a value/return.
- **Gate expensive transforms**: symbolic simplification (e.g., `sympy.simplify()`) can dominate runtime—make it optional or clearly document the cost.
- **Avoid unnecessary materialization/conversion**: validate input size *before* `map()`/list creation; don’t re-wrap inputs already in the expected type (e.g., `np.array(arr)` when `arr` is already `np.ndarray`).
- **Avoid double iteration**: combine validation with the main loop when that removes an extra pass.

Example patterns (correct-by-construction + faster):
```python
# 1) Avoid insert-at-front in recursion: use append + reverse
result = []
# ... DFS fills `result` with descendants-first
return list(reversed(result))

# 2) Compute expensive support once
candidate_counts = {}
for c in candidates:
    support = get_support(c, transactions)
    if support >= min_support:
        candidate_counts[c] = support

# 3) Check length before mapping
tokens = input().split()
if len(tokens) > MAX_SEQUENCE_LENGTH:
    ...
user_input = list(map(int, tokens))

# 4) Optional expensive simplify
def maybe_simplify(expr, *, simplify: bool = False):
    return sp.simplify(expr) if simplify else expr

# 5) Avoid redundant conversion
if not isinstance(arr, np.ndarray):
    arr = np.array(arr)
```

---

## Self-Documenting Naming Rules

<!-- source: TheAlgorithms/Python | topic: Naming Conventions | language: Python | updated: 2026-05-01 -->

Use self-documenting identifiers: variable/function/class names should explain intent without relying on comments, and avoid confusing or ambiguous abbreviations.

Practical rules:
- Prefer descriptive `snake_case` names for functions, parameters, and local variables (e.g., `duration`, `return_period`, `step_size`).
- Avoid single-letter identifiers for semantic values (use them only for loop counters like `i`/`j` in short loops).
- Do not shadow Python built-ins or common library names (e.g., avoid naming variables/params `sort`).
- If a comment says what a variable means, rename the variable to make that comment unnecessary.

Example (before/after):
```python
# Before
def trapezoidal_rule(f, boundary, steps):
    h = (boundary[1] - boundary[0]) / steps
    a = boundary[0]
    b = boundary[1]
    x_i = make_points(a, b, h)

# After
def trapezoidal_rule(
    f: callable,
    boundary: list[float],
    steps: int,
) -> float:
    lower_bound, upper_bound = boundary
    step_size = (upper_bound - lower_bound) / steps
    x_points = make_points(lower_bound, upper_bound, step_size)
    result = 0.0
    # ...
    return result
```
Apply the same principle to all algorithm modules: ensure names are clear to someone who only reads the code.

---

## Pure Functions and Main Guard

<!-- source: TheAlgorithms/Python | topic: Code Style | language: Python | updated: 2026-04-30 -->

Keep reusable code clean and production-ready: reusable/algorithmic functions should be side-effect free (no `print()`), and all executable/demo/driver code must be under an `if __name__ == "__main__":` guard. Also keep imports at the top and sorted/PEP8-compliant.

Example (move prints + examples):

```python
def quick_select(items: list[int], index: int) -> int:
    # reusable logic: no printing, no prompting
    ...


def _demo() -> None:
    prices = [7, 1, 5, 3, 6, 4]
    print("Example:", quick_select(prices, 3))


if __name__ == "__main__":
    _demo()
```

Checklist:
- No `print()`/debug logging in core algorithm/library functions (return values instead).
- Put example usage, manual tests, and script entry points behind `if __name__ == "__main__":`.
- Put all imports at the top of the file; sort/group them per lint rules.
- Ensure type hints and function signatures are consistent and non-redundant (don’t omit required annotations for public functions).

---

## Explicit Optional Nulls

<!-- source: TheAlgorithms/Python | topic: Null Handling | language: Python | updated: 2026-04-29 -->

When a value can be absent, represent that absence explicitly and consistently.

**Do**
- Use `Optional[...]`/`T | None` in type hints for nullable inputs, outputs, and pointers.
- Initialize missing references (e.g., children, root) to `None`—never to a placeholder like `self`.
- For empty inputs, set the owning state to `None` (or return early) rather than creating dummy nodes that look valid.
- Keep function return contracts consistent: if an API can’t produce a result, return `None` (or use a single sentinel), and type it accordingly.
- If `None` is only used to mean “use default behavior,” prefer a non-`None` default argument.

**Example (segment-tree style):**
```python
from dataclasses import dataclass
from typing import Optional

@dataclass
class Node:
    start: int
    end: int
    value: int = 0
    left: Optional["Node"] = None
    right: Optional["Node"] = None

class SegmentTree:
    def __init__(self, nums: list[int]) -> None:
        self.root: Optional[Node] = None
        if not nums:
            return
        self.root = self.build(0, len(nums) - 1, nums)
```

Applying this standard prevents null-reference bugs, removes confusing placeholder behavior, and makes absence handling readable and enforceable by both humans and type checkers.

---

## Null-Safe Defaults

<!-- source: freeCodeCamp/freeCodeCamp | topic: Null Handling | language: Markdown | updated: 2026-04-28 -->

Write code assuming inputs (arrays, objects, DOM nodes) may contain `undefined`, `null`, or “empty slots/holes”, and normalize them early with explicit defaults.

**Standards**
- **Guard reads**: when locating DOM nodes or accessing optional properties, use null-safe patterns (e.g., optional chaining) and avoid assuming existence.
- **Normalize missing fields**: if a required field might be absent (e.g., `zone`), assign a deterministic default (`"general"`).
- **Handle array holes explicitly**: if your logic iterates arrays, don’t assume all indices contain values—treat holes like missing entries and decide whether to skip/compact them.
- **Test the “empty” cases**: include tests for both `undefined` values and array holes (e.g., `[, ]`), not just one.

**Example**
```js
function groupByZone(actions) {
  return actions.reduce((acc, action) => {
    const zone = action?.item?.zone ?? 'general'; // default when missing/undefined
    (acc[zone] ??= []).push(action);
    return acc;
  }, {});
}

// Null-safe DOM access
const el = document.querySelector('.container > div');
console.assert(el?.classList.contains('output'));
console.assert(el?.classList.contains('hide'));

// Example for array-hole aware compaction
function compactFragments(arr) {
  return arr.filter(Boolean); // removes undefined/null and also skips holes
}
```

---

## Concurrency-safe async flows

<!-- source: freeCodeCamp/freeCodeCamp | topic: Concurrency | language: TSX | updated: 2026-04-21 -->

When UI actions can occur rapidly or in parallel (double-clicks, retries, rapid test submissions), treat them as concurrency problems: synchronize the triggering and centralize the side effects.

Apply two rules:
1) Guard “repeatable” actions (submit/reset/etc.) with stable synchronization and cleanup.
- Don’t inline-create debounced/locked functions in a way that changes across re-renders—this can weaken protection.
- Use a stable ref for the dispatch target and debounce it once; cancel pending debounced work on unmount.

```ts
const SUBMIT_DEBOUNCE_MS = 1000;

export function useSubmit() {
  const dispatch = useDispatch();

  const submitRef = useRef(() => dispatch(submitChallenge()));
  submitRef.current = () => dispatch(submitChallenge());

  const debouncedSubmitRef = useRef(
    debounce(() => submitRef.current(), SUBMIT_DEBOUNCE_MS, {
      leading: true,
      trailing: false,
    })
  );

  useEffect(() => {
    const debouncedSubmit = debouncedSubmitRef.current;
    return () => debouncedSubmit.cancel();
  }, []);

  return () => debouncedSubmitRef.current();
}
```

2) Centralize API + store mutation in a single orchestrator (e.g., saga).
- UI components should pass “intent” (what to delete/reset/submit) rather than directly mixing API calls with store updates.
- This reduces inconsistent state transitions and race conditions (including special responses like 204 where store updates may otherwise be skipped).

Result: fewer race-condition bugs, more deterministic behavior under fast user input and automated rapid submissions, and clearer ownership of async workflows.

---

## Mock Only What Matters

<!-- source: freeCodeCamp/freeCodeCamp | topic: Testing | language: TSX | updated: 2026-04-17 -->

When writing tests, avoid introducing unnecessary fakes/mocks that hide real integration behavior.

- If your goal is to validate how code interacts with DOM dependencies, don’t “fake” core event/data shapes more than needed; use the real DOM/events interface (or a higher-fidelity fixture) so failures reflect real breakage.
- Keep mocking minimal and scoped to the unit under test: hoist/stabilize only what must be shared or stable, and define the rest inline to prevent extra complexity and to reduce coupling to singleton/module state.

Example (minimal mocking in a hook test):

```ts
import { renderHook } from '@testing-library/react';
import { vi } from 'vitest';

const { mockDispatch } = vi.hoisted(() => ({
  mockDispatch: vi.fn(),
}));

// inline mock for the second dependency to keep the hook isolated and readable
vi.mock('./some-module', () => ({
  useSingleton: () => ({
    dispatch: mockDispatch,
    initialize: vi.fn(),
  }),
}));

// renderHook(...) 
```

Practical checklist:
- What behavior is the test asserting?
- Does the setup replace real interfaces with unrealistic fakes?
- Are there mocks/fixtures that aren’t required for the assertion? Remove or inline them.
- If a dependency changes (DOM structure/events/interaction contract), will this test fail in a meaningful way?

---

## Validate Block JSON

<!-- source: freeCodeCamp/freeCodeCamp | topic: CI/CD | language: Json | updated: 2026-04-07 -->

Ensure every `curriculum/structure/blocks/*.json` file matches the CI-validated schema and constraints.

- Remove deprecated/unused fields (e.g., `name`)—CI may reject these.
- Ensure required identifiers conform to CI rules (e.g., block/challenge `id` must be valid and not too short).
- If CI fails, fix the JSON payload in the same branch (don’t rely on retries).

Example (schema-compliant style):
```json
{
  "isUpcomingChange": false,
  "dashedName": "workshop-envelope-budget-app",
  "helpCategory": "HTML-CSS",
  "blockLayout": "challenge-grid",
  "blockLabel": "workshop",
  "challengeOrder": [
    { "id": "<valid-id-length-and-format>", "title": "Step 1" }
  ]
}
```

---

## Deterministic Array Algorithm Contracts

<!-- source: freeCodeCamp/freeCodeCamp | topic: Algorithms | language: Markdown | updated: 2026-04-02 -->

For algorithm-heavy code that transforms arrays (multi-step pipelines, scheduling, deduping, cyclic traversal), require clear, testable function contracts and deterministic behavior:

- **Input validation upfront**: if the input type/shape is invalid, return the specified neutral value immediately (often `[]`).
- **Pure transformations**: each helper should return a **new array** (and avoid mutating inputs) while adding or deriving only the fields required by the next step.
- **Deterministic ordering rules**: when deduplicating, define whether you keep the **first/earliest** occurrence (stable dedupe). When building schedules/orders, compute positions deterministically (e.g., 1-based `slot`).
- **Correct cyclic indexing**: when iterating through an array circularly, use modulo for wraparound: `nextIndex = (currentIndex + 1) % array.length`.

Example pattern (flatten → score → stable dedupe):
```js
function flattenPlaylists(playlists) {
  if (!Array.isArray(playlists)) return [];

  const out = [];
  playlists.forEach((pl, playlistIndex) => {
    if (!Array.isArray(pl)) return;
    pl.forEach((track, trackIndex) => {
      out.push({
        ...track,
        source: [playlistIndex, trackIndex],
      });
    });
  });
  return out;
}

function scoreTracks(tracks) {
  return tracks.map(t => ({
    ...t,
    score: t.votes * 10 - Math.abs(t.bpm - 120),
  }));
}

function dedupeTracks(tracks) {
  const seen = new Set();
  const out = [];
  for (const t of tracks) {
    if (seen.has(t.trackId)) continue;
    seen.add(t.trackId);
    out.push(t);
  }
  return out; // keeps the earliest occurrence
}
```

Apply this standard anytime you see multi-step array algorithms or any logic depending on order/cycles—make those rules explicit in the functions’ behavior.

---

## CI workflow correctness

<!-- source: TheAlgorithms/Python | topic: CI/CD | language: Yaml | updated: 2026-03-26 -->

{% raw %}
All CI workflows must be syntactically valid, reliably triggered, and logically non-redundant.

Apply these rules:
1) Every step must be valid: each `- name:` entry must include either `uses:` or `run:` (never both missing).
2) Condition + command belong together: put `if:` on the same step as the `run:` (or `uses:`).
3) Triggers must match the repo: ensure the referenced branches in `on: push` / `on: pull_request` actually exist; avoid `paths-ignore` patterns that skip directories containing code.
4) Version pinning clarity: when pinning a GitHub Action to a commit SHA, the inline comment must match the intended release version.
5) Avoid duplicate work: don’t rerun linters/tests already covered by dedicated lint/test workflows or pre-commit jobs.
6) Respect project runtime policy: don’t hardcode an older Python version if the project expects testing against the latest production CPython; align job installs with the intended uv dependency groups.

Example (valid conditional step):
```yaml
- name: Build docs artifact
  if: ${{ success() }}
  run: |
    scripts/build_directory_md.py 2>&1 | tee DIRECTORY.md
```
Example (pin comment matches intent):
```yaml
- name: Set up uv
  uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0
```
Example (sanity on triggers):
- Only ignore files/directories if they truly contain no executable/code paths required for CI, and only reference branches that exist in the repository.
{% endraw %}

---

## Use canonical invariants

<!-- source: freeCodeCamp/freeCodeCamp | topic: Algorithms | language: JavaScript | updated: 2026-03-18 -->

When implementing algorithmic parsing/validation, base ordering/state on the canonical structured source, and keep validation logic split by invariant (local vs global) with explicit intent.

How to apply:
- Prefer authoritative structured data over heuristic text scanning. If the algorithm needs “step order” or similar ordering/state, derive it from the relevant JSON (or other canonical artifact) rather than from frontmatter or partial text.
- If you have multiple checks that seem redundant, treat them as enforcing different invariants:
  - Local invariant (e.g., per-file constraint like “no single seed file has >2 markers”).
  - Global invariant (e.g., workshop constraint like “exactly 2 total markers across all seed files”).
- Document the invariant split inline so future refactors don’t remove a “redundant” check that actually guards a different failure mode.

Example pattern (sketch):
```js
const fs = require('fs');

function getStepOrder(blockJsonPath) {
  const block = JSON.parse(fs.readFileSync(blockJsonPath, 'utf8'));
  return block.steps.map(s => s.order); // derive ordering from canonical data
}

function isLastStep(stepOrder, currentOrder) {
  return currentOrder === Math.max(...stepOrder);
}

function validateSeeds(seeds) {
  // Local invariant: per-seed-file
  for (const seed of seeds) {
    const markers = findRegionMarkers(seed);
    if (markers > 2) throw new Error('Per-file: too many markers');
  }

  // Global invariant: across all seeds
  const totalMarkers = seeds.reduce((sum, seed) => sum + countMarkers(seed), 0);
  if (totalMarkers !== 2) throw new Error('Workshop: exactly two total markers');
}
```

This approach improves algorithmic reliability (correct ordering/state) and correctness of constraint enforcement (no accidental gaps from removing “seemingly redundant” checks).

---

## Prefer clear, semantic code

<!-- source: freeCodeCamp/freeCodeCamp | topic: Code Style | language: TSX | updated: 2026-03-11 -->

Write code that’s easy to read and matches intent (mutability, string composition, UI semantics), and remove obvious clutter.

Apply these rules:

1) Avoid reassignable variables
- Prefer `const` when a value isn’t reassigned.
```ts
const repository = curriculumLocale === 'english'
  ? 'freeCodeCamp'
  : 'i18n-curriculum';
```

2) Build static paths/strings directly
- For URL/path-like strings made of known segments, prefer array joining (or a single template literal) over nested `join(...)`/extra indirection.
```ts
const challengesFolder = ['blob', 'main', 'curriculum', 'challenges'].join('/');
const gitPath = [repository, challengesFolder, curriculumLocale, 'blocks', block, `${challengeId}.md'].join('/');
gitURL.pathname = gitURL.pathname + gitPath;
```

3) Don’t add redundant conditionals when UI state already guarantees behavior
- If a control is `disabled`, the handler usually doesn’t need guarding.
```tsx
<Button disabled={isClassroomAccount} onClick={updateIsClassroomAccount} />
```

4) Render links as links; actions as buttons
- If the user is navigating to/copying/opening a URL, use a link element/component. Avoid “button that opens a new tab” when a link is available—this improves accessibility and expected browser features.

5) Remove duplicate/unused imports
- Keep imports unique and ensure every import is used (e.g., don’t import the same symbol in multiple places).

---

## Use Config Safely

<!-- source: freeCodeCamp/freeCodeCamp | topic: Configurations | language: TSX | updated: 2026-03-10 -->

Treat configuration/feature-flag-driven logic as potentially different between tests and runtime, and standardize how you branch on it.

Apply this by:
1) Verify config-derived outputs with real environment values
- If you compose strings/URLs from config (e.g., base URL + path), ensure runtime values produce the expected final result.
- Don’t rely solely on tests that stub config differently—run locally with the real `GITHUB_LOCATION`/`env.json` setup and confirm the generated links actually work.

2) Prefer the standard feature-flag mechanism for UI
- When the project provides an abstraction (e.g., `IfFeatureEnabled`), use it for feature-controlled UI rather than mixing ad-hoc boolean wrappers that reduce readability and consistency.

3) Keep conditional UI layout consistent
- When rendering conditionally, ensure spacing/layout remains stable and visually intentional.

Example pattern (feature-controlled UI):
```tsx
<IfFeatureEnabled feature='classroom-mode'>
  <Spacer size='m' />
  <ClassroomMode
    isClassroomAccount={isClassroomAccount}
    updateIsClassroomAccount={updateIsClassroomAccount}
  />
</IfFeatureEnabled>
```

---

## Minimize API Roundtrips

<!-- source: freeCodeCamp/freeCodeCamp | topic: API | language: TSX | updated: 2026-02-09 -->

When the client performs a state-changing action, design the API contract so it can be completed in as few requests as possible—prefer batch-capable endpoints and responses that include what the client needs to update UI/state without additional “refresh” calls. Also, for one-way boolean updates where the server can infer intent, avoid unnecessary request bodies.

Apply this as follows:
- Prefer server-side batching: if the client currently loops per item (and adds delays/rate-limit workarounds), provide an endpoint that accepts an array of IDs.
- Avoid client re-fetches after mutations: don’t call a broad “fetch user/account” just to learn the mutation result; return the updated/derived data from the mutation endpoint.
- Simplify one-way updates: if an endpoint always sets a field to a constant (e.g., `true`), don’t require a payload that just repeats that constant.

Example (batch endpoint shape):
```ts
// Instead of calling per block with rate-limit delays
// await deleteResetModule({ blockId: currentBlock }) in a loop

// Prefer one request with all IDs
await deleteResetModules({ blockIds: blockIds });
```

Example (mutation returns data to update client state):
```ts
const res = await resetModule({ moduleId });
// res should include the updated state the UI needs
setStateFromResponse(res);
// Don’t call a separate fetchUser() just to refresh UI.
```

---

## Canonical Documentation Entries

<!-- source: EbookFoundation/free-programming-books | topic: Documentation | language: Markdown | updated: 2026-02-03 -->

When adding or updating documentation entries (e.g., course/resource lists), use canonical metadata and URLs so links don’t break, don’t leak tracking, and render correctly.

Apply this checklist:
- Use the exact title from the source (don’t invent/reshape titles).
- Always include the producer/creator/channel/author name where applicable.
- URL rules:
  - No shortened URLs.
  - For YouTube, prefer `www.youtube.com` **playlist** links over single videos.
  - Remove tracking/query params (e.g., `si=...`, `feature=...`, `&t=...`, `&list=...` duplicates when not part of a playlist canonical link).
- Markdown rules:
  - Escape `|` in titles as `\|`.
  - Avoid emojis in titles.
- Keep internal doc structure consistent (headings/anchors/categories/index) so navigation works.

Example (YouTube playlist bullet):
```md
* [React JS Tutorial Series (Kannada)](https://www.youtube.com/playlist?list=<PLAYLIST_ID>) - <Channel/Creator Name>
```
Example (escape pipe):
```md
* [Material UI Complete in One Video \| (Hindi)](https://www.youtube.com/playlist?list=<PLAYLIST_ID>) - <Creator>
```

---

## Avoid Unnecessary Type Assertions

<!-- source: freeCodeCamp/freeCodeCamp | topic: Code Style | language: TypeScript | updated: 2026-02-03 -->

In route/controller code, don’t rely on repeated `as` casts to satisfy TypeScript—normalize/validate types once, then keep the rest of the logic strongly typed.

Apply this style rule:
- If you see patterns like `(value as unknown[]).filter(...)` or `filteredX as never`, it’s a formatting/readability smell.
- Replace them with a single typed normalization/helper (or adjust the Prisma/type definitions) so the filtered result already has the right shape.

Example (mimic the proposed approach):
```ts
// Normalize once to the correct element shape
const normalizeChallenges = (arr: unknown) => arr as Array<{ id: string }>;

const filteredCompletedChallenges = normalizeChallenges(user.completedChallenges)
  .filter(c => !challengeIdsToReset.includes(c.id));

await fastify.prisma.user.update({
  where: { id: req.user!.id },
  data: {
    completedChallenges: filteredCompletedChallenges,
  },
});
```

---

## RESTful endpoint responses

<!-- source: freeCodeCamp/freeCodeCamp | topic: API | language: TypeScript | updated: 2026-02-03 -->

When designing API routes, make the HTTP method and response contract match the operation’s intent and the client’s needs.

- Pick the correct verb: use DELETE for destructive/reset-like removal semantics when appropriate, and reserve POST for creation/processing actions.
- Choose a standard response:
  - If nothing needs to be consumed by the client, return `204 No Content`.
  - If the client needs confirmation, return either the updated resource (e.g., updated `user`) or a minimal, explicit summary of what changed (e.g., which items were removed).
- Avoid returning payloads that are arbitrary or unlikely to be used; keep the response minimal and purposeful.

Example pattern:
```ts
fastify.delete('/account/reset-module', {
  schema: schemas.resetModule
}, async (req, reply) => {
  // ...remove/reset items
  return reply.code(204);
});

// OR if the client needs a summary:
return {
  blockId,
  completedChallengesRemoved,
  savedChallengesRemoved,
  partiallyCompletedChallengesRemoved
};
```

---

## Lint-Compliant Markdown Links

<!-- source: EbookFoundation/free-programming-books | topic: Code Style | language: Markdown | updated: 2025-11-07 -->

When adding/updating entries in markdown lists, follow the repository’s lint-safe formatting and platform/link conventions.

Checklist:
- Escape special markdown characters in titles/labels: use `\|` instead of `|`.
- Do not add stray Unicode control characters (e.g., RTL marks) to link text.
- Use the resource’s original title—don’t “improve” or invent names just to fit style.
- For YouTube entries, prefer playlist URLs when applicable and include the producer/creator as used elsewhere in the file.
- Keep entry format consistent across files (same `* [Title](URL) - Creator` pattern).
- Avoid emoji and other characters that can break lint/rendering.
- Follow ordering/structure requirements enforced by lint (alphabetical order in the section, correct blank lines, correct header levels).
- Follow URL formatting rules enforced by lint (e.g., remove trailing `/` when required).
- If mixing HTML and markdown, add appropriate spacing/newlines so markdown renders correctly (don’t rely on implicit formatting).

Example (correct pipe escaping):
```md
* [React JS Tutorial in Hindi \| React JS for Beginner to Advanced \| Step by Step Video Tutorials](https://www.youtube.com/playlist?list=PLjVLYmrlmjGdnIQKgnTeR1T9-1ltJEaJh) - WsCubeTech
```

Example (avoid invented titles/ensure lint-safe formatting):
```md
* [.NET Rocks!](https://dotnetrocks.com) - Carl Franklin, Richard Campbell (podcast)
```

---

## Never edit generated JSON

<!-- source: kamranahmedse/developer-roadmap | topic: CI/CD | language: Json | updated: 2025-10-19 -->

Treat any build/CI-generated JSON (and files under similar “public/…-content” paths) as read-only. Don’t patch them directly in PRs—changes will be overwritten or won’t propagate.

How to apply:
- Find the upstream source used by the generator (e.g., templates, content definitions, or the build script/config).
- Make the change there.
- Regenerate the JSON via the normal pipeline/build step and verify the output.

Example (PR rule of thumb):
- ❌ Commit to: `public/roadmap-content/*.json` (auto-generated output)
- ✅ Commit to: the generator input/template/source, then run the build to update the generated JSON automatically.

---

## Stateful Parsing Correctness

<!-- source: EbookFoundation/free-programming-books | topic: Algorithms | language: Python | updated: 2025-10-19 -->

When implementing stateful parsing (e.g., direction/context tracking with stacks), treat correctness as a property of the whole scan loop—not just the “main” match.

Apply these rules:
- Don’t use `continue` (or similar early-skip control flow) in ways that prevent subsequent tokens/characters on the same iteration/input segment from being processed. If multiple tags/tokens can exist close together, ensure nothing that could affect output/state is skipped.
- If a line can contain multiple relevant tags, extract *all* matches on that line and process them in textual order, updating your context stack deterministically (push on opening, pop on closing).
- Document the intent (especially why multiple tags on the same line must be handled) and the meaning of match groups/tuples so future edits don’t regress correctness.

Example pattern (process all `<div dir>` tags on a line, in order):
```py
# Find all opening and closing <div> tags on the line
div_tags = re.findall(
    r"(<div[^>]*dir=['\"](rtl|ltr)['\"][^>]*>|</div>)",
    line,
    re.IGNORECASE,
)

for tag, direction in div_tags:
    if tag.startswith('<div') and 'markdown="1"' in tag:
        block_context_stack.append(direction.lower())
    elif tag == '</div>' and len(block_context_stack) > 1:
        block_context_stack.pop()
```

Add/keep tests that cover: (1) multiple tags on the same line and (2) cases where skipping tokens would drop nearby output characters (e.g., punctuation around inline spans).

---

## Canonical IDs and Titles

<!-- source: EbookFoundation/free-programming-books | topic: Naming Conventions | language: Markdown | updated: 2025-10-09 -->

Adopt canonical naming rules for both **identifiers (anchors/ids)** and **display names (titles)** to prevent broken links and inconsistent labeling.

## Rules
1. **Anchor ids must be explicit and stable**
   - If a section/subsection is referenced by an in-page link, ensure there is an explicit matching `id`.
2. **Use consistent casing for ids**
   - Prefer **lowercase ids** (avoid relying on markdown-generated casing differences).
3. **Keep anchor sections ordered predictably**
   - When adding headings/anchors, place them in **alphabetical order** within their group.
4. **Do not invent or paraphrase resource titles**
   - Use the **exact title** provided by the resource/creator.
5. **Avoid honorifics/extra prefixes in names**
   - Don’t add titles like “Professor” or similar honorifics to the listed display name.

## Example (anchor/id)
```md
### <a id="yapay-zeka"></a>Yapay Zeka

<!-- later: link must match the id exactly -->
[Go to Yapay Zeka](#yapay-zeka)
```

## Example (title)
```md
<!-- Good: exact source title -->
* [TypeScript — Frontend & Backend (file setup, types, generics, React + TS)](https://github.com/...)

<!-- Avoid: modified/invented title -->
* [TypeScript Cheatsheet](https://github.com/...)  <!-- only if this is the exact resource title -->
```

---

## Encode International URLs

<!-- source: EbookFoundation/free-programming-books | topic: Security | language: Markdown | updated: 2025-10-04 -->

When adding or modifying external URLs, ensure international/non-ASCII URLs are **percent-encoded** (UTF-8 → percent-encoding). Do not treat “escape” as a vague idea—use proper URL encoding so links render correctly across clients and avoid malformed/ambiguous URL behavior.

Apply this during link updates:
- Percent-encode international characters in the URL path/query (e.g., Tamil, accented characters).
- Ensure the final URL string is valid and copy-pastable.

Example (conceptual):
```text
Incorrect (not encoded):  http://example.com/புத்தகம்?q=தேர்வு
Correct (encoded):        http://example.com/%E0%AE/....?q=%E0%AE/....
```

If you’re unsure, re-encode the URL using your language/runtime’s URL/URI utilities before committing documentation or code changes.

---

## Avoid stray commas

<!-- source: TheAlgorithms/Python | topic: Code Style | language: Yaml | updated: 2025-08-23 -->

When running linters/formatters in CI or scripts, keep command arguments syntactically precise and standardized—remove any stray or meaningless punctuation (like a standalone comma) and normalize whitespace so commands are unambiguous.

Also, standardize on the team’s chosen linter (e.g., use Ruff instead of Flake8 when Ruff is the agreed replacement) to keep behavior consistent across environments.

Example (CI lint step):
```yaml
- name: Lint code
  run: |
    uv run ruff check --output-format=github
```
Avoid patterns like:
```yaml
run: uv run ruff check , --output-format=github
```

---

## Use semantic names

<!-- source: TheAlgorithms/Python | topic: Naming Conventions | language: Yaml | updated: 2025-08-23 -->

Use intention-revealing, consistent, and unique names for CI workflow, jobs, and steps (avoid generic labels like `build`). Names should tell the reader what the unit actually does.

Apply:
- Workflow `name:`: describe the pipeline purpose (not “build”).
- Job `name:`: match the job’s responsibility; avoid multiple jobs called `build`.
- Step `name:`: explain the action; prefer specific labels that reflect the command/task.

Example (GitHub Actions):
```yaml
name: Build CI/CD Pipeline

jobs:
  build_and_test:
    name: Build and Test
    steps:
      - name: Checkout Repository
        uses: actions/checkout@v5
      - name: Set up uv
        uses: astral-sh/setup-uv@v3
      - name: Install dependencies
        run: uv sync --group=test

  directory_writer:
    name: Directory Writer
    # ...
```
This improves readability and reduces confusion when multiple workflows/jobs/steps exist.

---

## Enforce shared code style

<!-- source: kamranahmedse/developer-roadmap | topic: Code Style | language: Markdown | updated: 2025-07-29 -->

Keep style consistent by following the team’s codified rules for both formatting and language idioms, and enforce them via shared tooling.

Apply this as a checklist:
- Use the team’s shared style configuration (e.g., a `stylecop.json` checked into the repo) so formatting rules are the same for everyone and across IDEs.
- Respect whitespace/structure rules consistently (for example, maintain required blank lines around headings/sections in docs).
- Follow language-specific style/idiom constraints, not just “compiles”: e.g., in Go prefer `:=` only where it’s valid.

Go example (idioms):
```go
// Package/global: prefer var
var x int // zero value

func f() {
    y := 1          // ok: inside function
    if z := y + 1; true {
        _ = z       // ok: temp in if init
    }

    // Redeclare semantics: one variable must be new
    a, b := 1, 2
    a, b = 3, 4 // plain assignment
    a, c := 5, 6 // redeclare with := where one LHS name is new
}
```

---

## Semantic Precision In Algorithms

<!-- source: kamranahmedse/developer-roadmap | topic: Algorithms | language: Markdown | updated: 2025-06-24 -->

When writing documentation or implementing algorithm/data-structure logic, make the *semantics* unambiguous: state the defining invariants/behavior, keep each section aligned to its exact step in the workflow, and avoid language-level ambiguity that can change correctness.

Apply as follows:
- **Define invariants clearly**: for data structures, explicitly state the property the structure maintains (e.g., heap parent/child ordering) and the precise rule for relationships (e.g., array parent/child indices).
- **Include operational behavior & complexity**: document the expected time complexity for the key operations (peek vs insert/delete for heaps, etc.).
- **Align section scope to the pipeline**: if the topic is a multi-step process (e.g., vector search), ensure each subsection covers the correct step (indexing/storage first; then query embedding and similarity search).
- **Eliminate correctness-impacting semantic ambiguity in code**: when equality or type-dependent logic matters (common in algorithm implementations), use strict comparisons to prevent unintended coercion.

Example (language semantics that affect algorithm correctness):
```js
// Prefer strict equality to avoid coercion-based bugs in comparisons.
if (candidate === target) {
  // correct: value and type must match
}
```

Use this standard to guide review checklists for algorithm docs and implementations so contributors don’t accidentally change meaning while only “rephrasing” or reorganizing content.

---

## Validate Security Inputs

<!-- source: TheAlgorithms/Python | topic: Security | language: Python | updated: 2025-01-30 -->

Security-sensitive code should *fail fast* with explicit validation of inputs and security parameters. That means: (1) validate structure/format (e.g., exact length, allowed characters), (2) validate ranges per component (e.g., IPv4 octets must be 0–255), (3) validate logical invariants the algorithm assumes (e.g., arrival time ≤ deadline), and (4) in cryptography, clearly distinguish *public parameters* from *secret material* and ensure computations use the correct one (don’t derive a peer’s values from the wrong party’s parameter set or mistakenly treat a public parameter as secret).

Example pattern:

```python
def ip_to_decimal(ip_address: str) -> int:
    parts = ip_address.split(".")
    if len(parts) != 4:
        raise ValueError("Invalid IPv4 address format")

    octets = []
    for part in parts:
        if not part.isdigit():
            raise ValueError("Invalid IPv4 address: non-numeric octet")
        n = int(part)
        if not (0 <= n <= 255):
            raise ValueError("Invalid IPv4 address: octet out of range")
        octets.append(n)

    decimal_ip = 0
    for n in octets:
        decimal_ip = (decimal_ip << 8) + n
    return decimal_ip
```

Crypto-specific checklist:
- Document which parameters are public (e.g., agreed group prime/generator) vs private (e.g., ephemeral key).
- Ensure each party derives its secrets/values only from its own private material and uses the other side’s values only as public inputs.
- Enforce minimum security sizes (e.g., key sizes) and reject unsupported configurations early.

---

## Auth-Gated Validation

<!-- source: kamranahmedse/developer-roadmap | topic: Security | language: TSX | updated: 2025-01-20 -->

Apply security controls at the UI/component level and ensure input validation is centralized.

1) Auth-state gating (authorization/flow correctness)
- Don’t render or enable actions when the user’s authentication state makes them invalid. Check auth state at the component boundary.

```tsx
export function SubscribeToChangelog({ isLoggedIn }: { isLoggedIn: boolean }) {
  if (isLoggedIn) return null; // or an alternative message
  return <button onClick={/* show subscribe flow */}>Subscribe</button>;
}
```

2) Centralize validation rules (input validation consistency)
- Avoid duplicating “regex + length” checks across handlers/components. Either:
  - Put constraints into the regex and only call `.test(value)`, or
  - Create a single helper and reuse it everywhere.

```ts
const USERNAME_REGEX = /^[a-zA-Z0-9]{0,20}$/; // includes length constraint
export function isUsernameValid(value: string) {
  return USERNAME_REGEX.test(value);
}

// usage
const isValid = isUsernameValid(value);
```

This prevents unauthorized/incorrect flows from appearing to the user and reduces the risk of inconsistent validation logic across the codebase.

---

## Manage Generated Configs

<!-- source: kamranahmedse/developer-roadmap | topic: Configurations | language: Json | updated: 2024-12-30 -->

When working with configuration JSON files, treat them as tool- and schema-backed artifacts:

- **Never manually edit auto-generated configuration/content files.** If a change is required, update the generator/template or revert the diff.
- **Avoid direct JSON edits when the file is synchronized with an editor/tool state.** Make changes through the intended UI/tooling so the “editor state” and the “code state” remain consistent.
- **Validate config fields against the allowed schema/contract.** Ensure values use only supported options (e.g., a field whose type is restricted must not be set to an unsupported string).

Example pattern:
```json
// Bad: violates the config contract
{ "type": "DevOps Roadmap" }

// Good: use an allowed value
{ "type": "button" }
```

Process guidance:
- If a diff appears due to the tool (e.g., unexpected dimension/visual-property changes), **revert and re-apply via the supported workflow** rather than continuing manual tweaks.
- Add/enable schema validation (or a lightweight pre-commit check) so invalid configuration values fail fast before review.

---

## Environment variable defaults

<!-- source: avelino/awesome-go | topic: Configurations | language: Go | updated: 2024-11-27 -->

Configuration values should be externalized to environment variables with sensible defaults to avoid hard-coding values in source code. This approach improves flexibility, security, and maintainability by allowing different configurations across environments without code changes.

When accessing configuration through environment variables, always provide appropriate fallback values to ensure the application functions correctly even when optional environment variables are not set.

Example implementation:
```go
var (
    githubApiAuthorizationToken = os.Getenv("GITHUB_API_TOKEN")
    userAgent = getEnvWithDefault("USER_AGENT", "MyApp/1.0")
)

func getEnvWithDefault(key, defaultValue string) string {
    if value := os.Getenv(key); value != "" {
        return value
    }
    return defaultValue
}

// Usage in HTTP request
request.Header.Set("User-Agent", userAgent)
```

This pattern ensures that sensitive values like API tokens can be injected at runtime while maintaining reasonable defaults for non-sensitive configuration like user agent strings.

---

## Concise Performance Guidance

<!-- source: kamranahmedse/developer-roadmap | topic: Performance Optimization | language: Markdown | updated: 2024-11-24 -->

When writing performance optimization standards/docs, keep the lead section brief and immediately actionable: provide a short overview plus a checklist of the key techniques, and move any deep technical explanation into linked resources.

How to apply:
- Lead/overview (1 short paragraph): define the goal and mention the major performance dimension(s) you’re addressing (e.g., initial load, rendering/DOM overhead, memory/bundle size, bottlenecks/monitoring).
- Checklist bullets: include the practical “what to do” items relevant to the platform (e.g., lazy loading, avoid unnecessary re-renders, reduce bundle size, virtualize long lists, monitor/profiling, minimize dependencies).
- Learn-more links: detailed “how/why,” step-by-step explanations, and deeper background should live behind links (internal pages or external docs).

Example (Markdown template):
```md
## Performance Optimization (Overview)
To improve performance, focus on reducing initial load time, minimizing unnecessary work during rendering, and identifying bottlenecks early.

- Lazy-load components to reduce upfront cost
- Prevent unnecessary re-renders (use appropriate conditional rendering patterns)
- Reduce bundle size (code splitting, tree shaking)
- Virtualize long lists/tables to cut DOM overhead
- Monitor/profiling to find bottlenecks
- Minimize dependencies that increase payload/work

Learn more:
- [Resource A](https://...)
- [Resource B](https://...)
- [Resource C](https://...)
```

This ensures the document is fast to scan, consistent with performance best practices, and doesn’t bury developers in overly deep content where a quick orientation is expected.

---

## Accurate AI Content

<!-- source: kamranahmedse/developer-roadmap | topic: AI | language: Markdown | updated: 2024-11-04 -->

When writing AI/LLM-related documentation or roadmap material, ensure it (a) states model limitations precisely, (b) stays in the correct scope for the node/context, and (c) explains implementations in terms of the underlying pipeline (prefer pre-trained tools) rather than framework specifics.

Apply these rules:
- Don’t present LLM outputs/citations as guaranteed. If citations are mentioned, explicitly note hallucinated/incorrect citations and mitigation (improved retrieval, RAG, and human oversight).
- Distinguish error modes when relevant: faithfulness (output diverges from provided context/sources) vs factuality (unsupported/incorrect facts).
- Keep multimodal sections multimodal: describe how the model is used for vision/audio within multimodal AI, not generic “image/audio processing” theory.
- Prefer “use pre-trained models/tools” framing for roadmap content; avoid unnecessary CNN/RNN architecture detail unless the node is explicitly about that.
- For RAG/agent patterns, describe the end-to-end steps (chunking → embeddings → store in vector DB → embed the query → similarity search → provide retrieved context), without requiring a specific library.

Example (claiming citations safely):
- Instead of: “The model will cite sources correctly.”
- Use: “LLMs may generate inaccurate or fictitious citations; use retrieval (RAG) plus verification/human oversight when citations matter.”

---

## Doc Intro And Links

<!-- source: kamranahmedse/developer-roadmap | topic: Documentation | language: Markdown | updated: 2024-10-17 -->

For roadmap/technical documentation pages, follow these rules:

- **Use correct Markdown structure**: prefer headings (e.g., `## Section`) over HTML line breaks like `<br/>`.
- **Keep pages intro-only**: when the page is meant to be a brief overview, **avoid adding code examples**; instead, explain the concept briefly and **redirect to external resources**.
- **Follow strict “resources” link conventions**:
  - Use the correct **link type tag** (e.g., `@article`, `@official`, `@roadmap`) for the resource.
  - Prefer **official** sources first; include a **small number of supporting article links** (e.g., ~2), rather than many.
  - Ensure URLs are in the correct form for your system:
    - If the environment requires copy/paste compatibility, keep **full URLs**.
    - If other pages use paths, keep the expected path structure consistently.

Example (intro without code + clean heading + resources):

```md
## Example (concept only)

This page provides a brief introduction to the concept and what it’s used for.
For deeper details and usage, see the resources below.

Learn more from the following resources:

- [@official@Concept Overview](https://example.com/official)
- [@article@Concept Deep Dive](https://example.com/deep-dive)
- [@article@Best Practices](https://example.com/best-practices)
```

Applying this consistently will improve readability, reduce duplicated content, and prevent broken/incorrect resource links.

---

## Use Approved Naming

<!-- source: kamranahmedse/developer-roadmap | topic: Naming Conventions | language: Markdown | updated: 2024-10-11 -->

Use precise, guideline-approved naming for identifiers (tags), technical terminology, and headings—so names are unambiguous, consistent, and match the actual meaning.

Apply this by:
- Tags/identifiers: Only use tag names that are valid and supported by the project’s contribution guide; don’t invent or repurpose tags. Ensure the tag is appropriate for the resource’s type/category.
- Technical terms: Use terminology that accurately reflects the concept and readers’ expectations (prefer “cache/caches” when the mechanism is caching; avoid unclear synonyms).
- Structural headings/categories: Follow the established naming/format patterns used elsewhere in the repo for section/category titles.

Examples:
- Tag naming (before → after):
  - `[@website@Cursor]` → `[@official@Cursor]` (when the contribution guide/category expects an “official” tag)
- Technical wording:
  - “`useMemo`… memorizes the result” → “`useMemo`… memoizes (i.e., caches) the result” / “caches the result” (only if it’s accurate and clearer to readers)
- Category/heading naming:
  - Don’t introduce one-off heading text that breaks the repo’s established category naming pattern; align with the documented example structure used by similar pages.

---

## Consistent Network Docs

<!-- source: kamranahmedse/developer-roadmap | topic: Networking | language: Markdown | updated: 2024-10-07 -->

Ensure all networking-related documentation uses consistent terminology, clean markdown formatting, and readable structure.

Apply this standard to any page covering protocols/features like Pub/Sub, WebSockets, SSE, MQTT, etc. 

- Use consistent terms and capitalization (e.g., “real-time”, “WebSockets”).
- Structure content with clear headings and short sections (concept → how it works → key commands/approaches).
- Keep markdown formatting hygienic (e.g., always end files with a trailing newline).
- When adding educational material, include at least one trusted external resource link (official docs or a reputable reference).

Example (pattern to follow in Markdown):
```md
# Topic Title

## What is topic?
Short, plain-language definition of the networking concept.

## How it works
1–3 sentences describing the flow/behavior.

## Key commands / options
- `COMMAND_1`
- `COMMAND_2`

Learn more from the following resources:
- [@official@Topic documentation](https://example.com)
```

---

## Idiomatic Style Commands

<!-- source: TheAlgorithms/Python | topic: Code Style | language: Markdown | updated: 2024-10-05 -->

When writing style guidance (including README/CONTRIBUTING snippets), keep examples concise and readable:

1) Use idiomatic tool invocations (avoid redundant arguments)
- Don’t include “current directory” arguments if the tool already defaults to the working directory.
- Prefer the documented, explicit subcommand form when required.

Example:
```bash
# Prefer (defaults to current directory)
ruff check

# Only specify a path when you truly need it
ruff check path/to/package
```

2) Format lists in sentences with consistent punctuation
- Use clear separators and an Oxford comma when listing multiple items (e.g., “filter, and reduce”) to prevent ambiguity.

Example:
```md
List comprehensions and generators are preferred over the use of `lambda`, `map`, `filter`, and `reduce`.
```

---

## Categorize by primary purpose

<!-- source: avelino/awesome-go | topic: Configurations | language: Markdown | updated: 2024-10-04 -->

When organizing configuration tools, environment management utilities, and settings-related projects, classify them based on their primary function and intended use case rather than their implementation details or secondary benefits. This ensures clear, consistent categorization that helps developers quickly identify the right tools for their configuration needs.

For example, a dependency injection library that uses reflection should be categorized under "Dependency Injection" rather than "Reflection" because dependency injection is its primary purpose. Similarly, when documenting configuration management tools, focus on what they primarily accomplish (environment management, config file handling, feature flags) rather than the underlying technology they use.

This approach prevents confusion and maintains logical organization where developers can intuitively find tools based on what they need to accomplish, not how the tools work internally. Apply this principle when creating configuration documentation, tool recommendations, and project categorization within your development environment.

---

## Fail-Fast CI/CD Steps

<!-- source: kamranahmedse/developer-roadmap | topic: CI/CD | language: Markdown | updated: 2024-08-27 -->

When building CI/CD pipelines, keep them scope-focused and deterministic, and add explicit quality gates so failures stop the deployment.

Apply:
- Put workflows in the conventional location and naming your team standard expects (e.g., `.github/workflows/main.yml`).
- Keep the CI/CD goal minimal (avoid extra tooling/framework bootstraps when the purpose is learning/automation).
- Run formatting/validation before deployment (e.g., `terraform fmt` + `terraform validate`), and structure steps in a clear order (`init → plan → apply`-style).
- Ensure any step error fails the workflow and prevents deploy (default GitHub Actions behavior already stops on non-zero exit codes).

Example (GitHub Actions):
```yaml
name: CI/CD
on: [push]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Build/Test
        run: |
          echo "run tests/build here"

      - name: Validate (fail fast)
        run: |
          terraform fmt -check
          terraform validate

      - name: Deploy
        if: success()
        run: |
          terraform init
          terraform plan -out=tfplan
          terraform apply -auto-approve tfplan
```

---

## Treat Untrusted Data Safely

<!-- source: kamranahmedse/developer-roadmap | topic: Security | language: Markdown | updated: 2024-08-18 -->

Security rule: Treat anything from the client (sessions, form fields, query params, template-bound values) as untrusted at runtime. Enforce safety on the server and use framework safe defaults for output encoding/sanitization. Only use “bypass”/escape hatches when you can prove the value’s origin and safety, and document that proof.

How to apply
- Authentication/session handling: On every request that depends on a user session, validate the session identifier server-side; invalidate/destroy it on logout.
- Input validation: Do not rely on TypeScript types for client input safety. Validate at runtime with a schema validator (e.g., Zod) for forms, API contracts, and persisted data.
- Output safety (XSS): Use the framework’s default escaping/sanitization for template interpolation/bindings.
- Narrow trust exceptions: If you must disable sanitization (e.g., Angular’s DomSanitizer bypass*), only do it after you inspected how the value was created and verified it cannot contain attacker-controlled payloads. If you can’t prove that, don’t bypass.

Example patterns
- Runtime input validation (Zod):
```ts
import { z } from "zod";

const LoginSchema = z.object({
  email: z.string().email(),
  password: z.string().min(1),
});

export function parseLogin(body: unknown) {
  return LoginSchema.parse(body); // runtime validation
}
```
- XSS-safe output (Angular):
  - Prefer normal template bindings/interpolation so Angular sanitizes/escapes by default.
- Risky bypass guarded by proof (Angular):
```ts
import { DomSanitizer } from "@angular/platform-browser";

export class ExampleComponent {
  trustedUrl: any;

  constructor(private sanitizer: DomSanitizer) {
    // Only bypass when you *proved* the value is not attacker-controlled
    // and you constructed it from trusted sources.
    const trusted = "https://example.com/safe-path";
    this.trustedUrl = this.sanitizer.bypassSecurityTrustUrl(trusted);
  }
}
```

Team checklist
- [ ] Server validates session IDs on protected endpoints
- [ ] All external inputs are validated at runtime with schemas
- [ ] UI output uses safe defaults (escaping/sanitization)
- [ ] Sanitization bypasses are prohibited unless a documented, verifiable safety check exists

---

## Valid Angular Examples

<!-- source: kamranahmedse/developer-roadmap | topic: Angular | language: Markdown | updated: 2024-08-15 -->

When adding Angular examples (docs, snippets, templates), ensure they are both *syntactically/semantically valid* and shown in the *correct template context*.

Key rules:
- **Signals in conditionals:** If a condition depends on a signal, **call** the signal (e.g., `count()`), rather than using the signal object directly.
- **Template blocks:** Show `@if` usage in an Angular **template/HTML** context (not in TS/logic examples), using valid template syntax.
- **Avoid misleading docs:** Don’t include examples that are known to always be truthy or otherwise incorrect; keep explanatory text and formatting clear.

Example (template context):
```html
<div class="user-container">
  @if (count() === 1) {
    <b>Count is 1</b>
  } @else {
    <b>Count is not 1</b>
  }
</div>
```

(And ensure `count` is a signal defined in the component, e.g., `const count = signal(0);`.)

---

## Enforce coverage thresholds

<!-- source: avelino/awesome-go | topic: Testing | language: Markdown | updated: 2024-08-13 -->

All code contributions must meet a minimum test coverage threshold of 80% before being accepted. This ensures adequate testing and helps maintain code quality standards across the project.

When reviewing code or adding new libraries, verify that test coverage meets or exceeds the 80% requirement. Coverage below this threshold should result in a request for additional tests before approval.

Example feedback:
```
Test coverage: 72%, the minimum required coverage is 80%.
```

This standard helps ensure that new code is properly tested and reduces the risk of introducing bugs into the codebase. Teams should configure their CI/CD pipelines to automatically check coverage and fail builds that don't meet this threshold.

---

## exported functions documentation

<!-- source: avelino/awesome-go | topic: Documentation | language: Markdown | updated: 2024-08-12 -->

All exported functions, types, and methods must include Go-style documentation comments that clearly explain their purpose, parameters, return values, and usage. This is a fundamental requirement for code quality and maintainability.

The documentation comments should:
- Start with the function/type name
- Provide a clear, concise explanation of what it does
- Document all parameters and return values
- Include usage examples when helpful
- Be written in English for broad accessibility

Example of proper Go-style documentation:

```go
// Get makes an HTTP GET request through the proxy pool with automatic
// retries and load balancing. It returns the response body and any error
// encountered during the request.
func Get(url string) (*http.Response, error) {
    // implementation
}

// Client represents an HTTP client with proxy pool capabilities
// for fault tolerance and load balancing.
type Client struct {
    // fields
}
```

This requirement ensures that all public APIs are self-documenting and accessible to other developers. Projects lacking proper documentation comments for exported elements should not be accepted until this standard is met, as it directly impacts the usability and professional quality of the codebase.

---

## React Docs With Scope

<!-- source: kamranahmedse/developer-roadmap | topic: React | language: Markdown | updated: 2024-08-02 -->

When adding or updating React documentation, include usage-scoped, actionable guidance—not just headings.

Apply this checklist:
- **Purpose (what it is):** Start with a plain-language definition.
- **Why/impact (so what):** Explain the practical effect (e.g., performance/re-render behavior).
- **Scope/boundaries (when not to use):** Explicitly state where it belongs and who should/shouldn’t import/use it.
- **Authoritative resources:** Link to official React documentation plus 1–2 reputable deep dives.
- **Markdown hygiene:** Ensure the file is well-formed (e.g., end with a newline).

Example (pattern):
```md
`someHook` is a React hook that ...

Use it to ...
Avoid using it when ...

Resources:
- React docs: https://react.dev/... 
- More: https://...
```

---

## optimize CI efficiency

<!-- source: avelino/awesome-go | topic: CI/CD | language: Yaml | updated: 2024-06-03 -->

Optimize CI/CD pipelines by minimizing resource usage and avoiding unnecessary operations. Use lightweight package alternatives when possible (e.g., `vim-nox` instead of `vim` for text processing), implement conditional execution to run steps only when relevant files change, and leverage automatic dependency resolution instead of manual listings.

For package optimization, prefer minimal variants:
```yaml
- name: Install Vim
  run: apt-get update; apt-get install -y vim-nox;
```

For conditional execution, use file change detection:
```yaml
- name: Verify Changed Files
  uses: tj-actions/verify-changed-files@v16
  with:
    files_ignore: |
      *.md
```

For dependency management, use automatic resolution:
```yaml
- name: Get dependencies
  run: go get -t -v ./...
```

This approach reduces CI execution time, minimizes resource consumption, and prevents unnecessary workflow runs while maintaining functionality. It's particularly important for repositories with frequent contributions that don't affect core functionality.

---

## Vet dependency supply chains

<!-- source: avelino/awesome-go | topic: Security | language: Markdown | updated: 2024-05-05 -->

When adding new dependencies, especially security-related ones, thoroughly evaluate them for supply chain attack risks. Look for red flags such as: repositories with many empty or automated commits, lack of transparent build processes (prefer GitHub Actions over opaque automation), use of unofficial forks instead of original packages, and suspicious account activity patterns.

Before accepting any dependency, verify:
- The repository has a clean commit history with meaningful changes
- Build and release processes are transparent and auditable  
- Official packages are used rather than forks when available
- The maintainer account shows legitimate development patterns

Example of concerning patterns to reject:
```
// Red flags identified in review:
- Empty commits: "c1a4854ffb9e83f903469490b44d640f233889c8"
- Account automation without visible GitHub Actions
- Packaging unofficial Go fork of asciinema instead of official version
- Underlying tracker with suspicious commit patterns
```

Supply chain attacks are a critical security vector - taking time to properly vet dependencies protects the entire ecosystem from potential compromise.

---

## Simplify CI scripting

<!-- source: EbookFoundation/free-programming-books | topic: CI/CD | language: Yaml | updated: 2023-10-21 -->

Keep CI/CD workflow steps readable and maintainable by consolidating repeated commands and using basic shell utilities for log processing.

Apply these rules:
- Consolidate repeated tool invocations into one command where supported (e.g., pass multiple paths at once).
- For creating empty files, use `touch file` rather than `cat > file`.
- For simple transformations/filters of a log, prefer bash + coreutils (e.g., `sed`, `uniq`) over adding a JavaScript cleanup step.

Example (PR log cleanup + artifact):
```sh
# Run lint and capture output
fpb-lint ./books/ &>> output.log || echo "Analyzing..."
fpb-lint ./casts/ &>> output.log || echo "Analyzing..."
fpb-lint ./courses/ &>> output.log || echo "Analyzing..."
fpb-lint ./more/ &>> output.log || echo "Analyzing..."

# Prepare artifact
mkdir -p ./pr
echo "$PR_URL" > ./pr/PRurl

# Bash cleanup (single-line transformation + dedupe)
cat output.log | sed -E 's:/home/runner/work/free-programming-books/|⚠.+::' | uniq > ./pr/error.log
```
If the cleanup logic becomes complex enough that shell becomes unreadable, then (and only then) consider a script—but default to the simplest working approach.

---

## Least-privilege Actions tokens

<!-- source: EbookFoundation/free-programming-books | topic: Security | language: Yaml | updated: 2023-10-21 -->

Treat CI workflow tokens as sensitive credentials: configure GitHub Actions `permissions` explicitly and keep token usage minimal.

Apply this standard when workflows need to create PR comments/reviews:
1) **Do not use insecure token workarounds** that broaden or misuse `GITHUB_TOKEN`.
2) **Split producer/consumer logic into separate workflows**: have one workflow generate the content and upload it as an **artifact**, then a second workflow reads that artifact and performs the PR write.
3) **Declare least-privilege permissions at the job level**. If a job comments on PRs, set only what’s needed (e.g., `pull-requests: write`). Avoid “write by default” repo settings for public repos.

Example (job-level permissions + artifact-based handoff):
```yaml
# consumer workflow: posts PR comment/review
on:
  workflow_run:
    workflows: ["free-programming-books-lint"]
    types: [completed]

jobs:
  post:
    permissions:
      pull-requests: write
    steps:
      - name: Download artifact from producer
        uses: actions/download-artifact@v4
        with:
          name: pr-message
      - name: Post message to PR
        run: |
          # read file produced earlier and use it to comment
          MSG_FILE=./message.txt
          cat "$MSG_FILE"
          # call GitHub API using default GITHUB_TOKEN with only PR write permission
```
This prevents authorization failures while reducing the blast radius of the token in CI/CD (a core security best practice for authentication/authorization in workflows).

---

## Verify markdown sanitization

<!-- source: avelino/awesome-go | topic: Security | language: Go | updated: 2017-03-29 -->

When processing markdown content, always verify what sanitization your chosen markdown library provides to prevent XSS vulnerabilities while avoiding redundant security measures. Some libraries like `github_flavored_markdown` include built-in sanitization, while others like `blackfriday` require explicit sanitization of their output.

Before adding sanitization calls, check the library documentation to understand its security features. For libraries without built-in sanitization:

```go
// blackfriday requires explicit sanitization
body := string(blackfriday.MarkdownCommon(input))
sanitized := bluemonday.UGCPolicy().SanitizeBytes([]byte(body))
```

For libraries with built-in sanitization, avoid double-sanitization:

```go
// github_flavored_markdown already sanitizes - no additional sanitization needed
body := string(gfm.Markdown(input))
```

This prevents both security gaps from missing sanitization and performance issues from redundant sanitization calls.

---

## Consistent Markdown Tables

<!-- source: ossu/computer-science | topic: Documentation | language: Markdown | updated: 2016-10-13 -->

When adding or editing tables in documentation, ensure the Markdown table is both syntactically continuous (so rows actually belong to the table) and stylististically consistent with existing docs.

Apply these rules:
- Don’t insert extra/blank lines between the table header, separator row, and the data rows; a stray line can cause later entries to render outside the table.
- Match the existing column order and header/alignment pattern used in the surrounding documentation.
- Use the same header + separator format across related files.

Example (use the same structure/pattern as the surrounding docs):
```md
Courses | Duration | Effort
:-- | :--: | :--:
[Machine Learning by Andrew Ng](https://www.coursera.org/learn/machine-learning) | - | -
```
If a row appears missing in the rendered preview, first check for stray/extra lines that break the table block, then verify the header/separator pattern matches the established one.

---

## Verify URL security and validity

<!-- source: avelino/awesome-go | topic: Networking | language: Markdown | updated: 2015-10-23 -->

Always ensure external URLs use HTTPS when available and verify that links resolve correctly before including them in documentation or code. HTTP links expose users to potential security risks through unencrypted connections, while broken or incorrect URLs create poor user experience and may indicate outdated dependencies.

When adding external links:
1. Prefer HTTPS over HTTP for security (e.g., use `https://bit.ly/go-slack-signup` instead of `http://bit.ly/go-slack-signup`)
2. Test that URLs actually resolve to the intended resource
3. For repository links, verify the correct path (e.g., `https://github.com/anacrolix/torrent/tree/master/dht` for source code or `https://godoc.org/github.com/anacrolix/torrent/dht` for documentation)

This practice protects users from security vulnerabilities and ensures reliable access to referenced resources.

---

## Follow Go style guidelines

<!-- source: avelino/awesome-go | topic: Code Style | language: Markdown | updated: 2015-07-05 -->

Code should adhere to the recommended Go style guidelines as outlined in the official Go Code Review Comments. While perfect adherence isn't always required, aim for minimal golint issues and follow established Go conventions for naming, formatting, and code organization.

High-quality Go code typically follows these standards naturally, and requiring this adherence helps filter out packages where insufficient care was taken in code quality. For existing, well-established packages, some flexibility may be acceptable, but new code should strive to follow these guidelines closely.

Consider using automated tools like golint or services like goreportcard.com to validate style compliance, though remember that these tools provide suggestions rather than absolute requirements. The goal is readable, idiomatic Go code that follows community standards.
