Code Golf: Extract Shared File-header Logic In Report

by Jule 54 views
Code Golf: Extract Shared File-header Logic In Report

Discussion category nwyin, pycfg-rs

In Rust report writers across active codebases, the file-header pattern appears repeatedly - often verbatim across functions. Three report generators all use nearly identical code to print a file header and separator, creating redundant boilerplate. This repetition isn’t just messy - it slows iteration and increases error risk.

Here is the deal: a single reusable function can eliminate the duplication by accepting a closure for body logic. This approach keeps the header logic centralized, crisp, and easy to modify.

The pattern appears in three key functions, each printing # file: <filename>\n\n once per report:

  • write_function_list_report lists files starting line 447.
  • write_summary_report follows a similar structure at line 472.
  • write_diagnostics_report adds a lighter touch at line 521 but keeps identical header code.

Each uses the same conditional header logic - showing file headers only if more than one file exists - yet repeats the same \n line + # file: block. This repetition adds nearly 12 lines across the three functions.

Beyond surface similarity, a hidden detail emerges: the header code is nearly identical in syntax and intent, not just structure. That means a closure-based helper becomes the perfect solution - replacing repeated strings with a single call.

This isn’t just about saving lines. It’s about clarity. When changes to the header format are needed, a single update propagates everywhere. Developers notice faster, mistakes shrink, and teams align on consistent output. Next time you write a report, ask: is this header logic worth repeating? The answer is often yes.

The bottom line: centralize file headers with a reusable closure. It cuts redundancy, strengthens maintainability, and keeps code clean. When every report shares a file header, do you repeat the same lines - or build once, adapt always?