Ch6.15: Best Practices for Functions

1. Keep functions short and focused

A function should do one thing well. If a function grows too large or tries to do too many things, split it into smaller functions.

2. Prefer clear names

A function name should describe what the function does. Avoid abbreviations unless they are universally understood.

3. Avoid unnecessary lambdas

Lambdas are convenient, but creating many identical lambdas can increase code size. Prefer reusing the same lambda or writing a normal function when the logic is simple.

4. Use captureless lambdas for callbacks

Captureless lambdas can be used as function pointers. If you need captures, consider whether a normal function or a different design is clearer.

5. Avoid deep recursion

Recursion uses the call stack. Deep recursion can cause stack overflow. Prefer loops when the depth is large or unpredictable.

6. Use fast_io view types instead of raw pointers

::fast_io::span, ::fast_io::string_view, ::fast_io::cstring_view, and ::fast_io::index_span provide safer and clearer function parameters than raw pointers or C‑style arrays.

7. Avoid unnecessary copying

Pass large objects by reference when possible. Avoid copying unless you truly need a separate copy.

8. Keep function signatures simple

Prefer a small number of parameters. If a function needs many parameters, consider grouping related values together or rethinking the design.

9. Use early returns for clarity

Early returns can make code easier to read by handling special cases first.


int divide(int a, int b)
{
    if(b == 0)
        ::fast_io::fast_terminate();
    return a / b;
}

10. Document assumptions

If a function assumes something (e.g., “pointer must not be null”), document it clearly. This prevents misuse and makes your code easier to maintain.

Key takeaways