Clean as You Code Practice
- Clean as You Code is a continuous practice that ensures code remains legible, maintainable, and safe to evolve by integrating refactoring and quality checks at the point of creation.
- It emphasizes architectural decoupling through dependency inversion and clear interface abstractions to reduce technical debt and enhance modularity.
- Empirical studies and AI research demonstrate that cleaner code improves navigational efficiency, reduces cognitive load, and boosts automated code-generation performance.
Searching arXiv for recent and relevant papers on clean code, code cleanliness, refactoring, technical debt, and linting. Clean as You Code denotes a software-quality practice in which code is kept continuously legible, analyzable, and safe to evolve at the point of creation or modification, rather than being deferred to episodic cleanup. Across the literature, the phrase spans several related but non-identical ideas: the Boy Scout Rule and continuous refactoring in practitioner discourse; architectural decoupling through explicit interfaces and dependency inversion; prevention-oriented management of technical debt in new code; static detection of bugs and code smells during development; and, more recently, the effect of code cleanliness on coding agents, code-generation models, and automated refactoring pipelines (Ljung et al., 2022, Brown et al., 2021, Digkas et al., 2020, Trivedi et al., 19 May 2026, Jain et al., 2023, Xue et al., 16 Aug 2025).
1. Conceptual foundations
In practitioner-oriented work, Clean as You Code is framed as a set of principles, habits, and tool-supported rituals intended to keep code continuously legible, safe to evolve, and resilient to change. The survey literature associates it with a catalog of Clean Code principles extracted from Martin’s book and supporting studies, including the Boy Scout Rule, KISS, OCP, minimizing nesting, meaningful names, DRY, command–query separation, SRP, high cohesion with low coupling, and focused tests (Ljung et al., 2022). In that formulation, the central norm is not merely “write clean code,” but “leave code in better shape than its intake form,” which turns cleanliness into an incremental maintenance discipline rather than a one-time redesign.
A second strand defines cleanliness operationally through measurable properties. One study quantifies code cleanliness along two axes measured by SonarQube Enterprise: static-analysis rule violations and cognitive complexity. It defines issue density and cognitive-complexity density per thousand non-comment lines of code, thereby turning cleanliness into a property amenable to controlled comparison across repositories that otherwise share architecture, dependencies, build process, and externally observable behavior (Trivedi et al., 19 May 2026). A related technical-debt perspective defines Technical Debt Density as normalized remediation effort per line of code, , and studies how new, deleted, and modified code affect density over time (Digkas et al., 2020).
These definitions imply that Clean as You Code is not a single doctrine. It can refer to local readability and naming, to structural decomposition and interface design, to static-analysis conformance, or to statistical properties of new code relative to legacy code. A plausible implication is that the term functions as an umbrella concept whose concrete interpretation depends on whether the target problem is maintainability, extensibility, technical-debt control, educational feedback, or AI-system efficiency.
2. Architectural interpretation: decoupling, interfaces, and extensibility
A strong architectural interpretation appears in the refactoring of the Whitby Intelligent Tutoring System from a Prolog module system into Logtalk. Before refactoring, OWLSAI tightly coupled the Situation Calculus reasoner with domain-specific fluents and actions, mixed ontology-authoring code with scaffolding code, and exhibited circular dependencies such as kb_manager ↔ oscar ↔ …. This structure was described as violating several SOLID principles: Single Responsibility, Open-Closed, Liskov Substitution and Interface Segregation, and especially Dependency Inversion, because high-level situation queries depended on concrete fluents and actions (Brown et al., 2021).
The refactoring re-expressed those relationships through Logtalk protocols and categories. The principal interfaces were action_protocol, fluent_protocol, s0_protocol, and intervention_protocol, each declaring predicate signatures only; implementations were provided by objects or categories that conform to them. Categories such as sitcalc_actions and sitcalc_fluents encapsulated default dispatch behavior, including do/2, poss/2, and holds/2, while the core Situation Calculus library used reflective predicates such as conforms_to_protocol/2 and current_object/1 to discover available actions and fluents without binding directly to concrete components (Brown et al., 2021).
The post-refactoring architecture inverted dependencies. SitCalc had no dependencies; OntologyAuthoring and Scaffolding depended on SitCalc and implemented s0_protocol and intervention_protocol; Whitby application objects depended on OntologyAuthoring and Scaffolding; and the UI sat above those layers. All arrows went from concrete components to protocol interfaces, and from high-level components to interfaces, never directly to low-level modules (Brown et al., 2021). In this setting, Clean as You Code means introducing interface abstractions early, inverting dependencies, grouping related behavior in reusable components, extracting domain-agnostic logic into standalone libraries, and maintaining acyclic dependency graphs.
The Whitby evaluation connected that interpretation to concrete structural outcomes. Logic-only code grew from approximately 8,000 LoC in 12 modules to approximately 10,000 LoC in 4 application objects plus 3 extracted libraries, while the number of reusable components increased from 0 shared libraries to 3 reusable libraries: SitCalc, OntologyAuthoring, and Scaffolding. Average dependency count fell from approximately 4.2 fan-in/out per module with cycles to approximately 2.0 dependencies per object without cycles, and adding a new domain-specific fluent changed from approximately 50 LoC in 3 modules plus manual updates to Golog imports to approximately 12 LoC in one object implementing fluent_protocol, with no core changes (Brown et al., 2021). This suggests that, in architectural contexts, cleanliness is inseparable from substitution boundaries and change isolation.
3. Clean new code, technical debt, and the economics of prevention
A prevention-oriented formulation treats Clean as You Code as a policy for controlling technical debt by constraining the quality of newly added artifacts. In a study of 27 Apache Software Foundation Java projects comprising 66,661 classes and 56,890 commits, new code was compared to existing code using method-level SonarQube code-smell remediation effort. The analysis decomposed the change in Technical Debt Density into contributions from new, deleted, and modified methods, with (Digkas et al., 2020).
The principal empirical result was that, across the 27 projects, between 61% and 86% of commits added new code whose density was lower than the host code, with median approximately 76.6%. For new methods in existing classes, the median was negative in 26 of 27 projects. New code showed a substantial association with system-level density change, with average and in 26 of 27 projects, although modified code exhibited an even stronger association, with (Digkas et al., 2020). The deletion of code was less predictive, with and significance in 11 of 27 projects.
The governance dimension was also explicit. Projects that discussed code quality and refactoring in board or PMC meetings exhibited a median 80.0% rate of cleaner-new-code commits, versus 75.0% otherwise, a difference of approximately 5.0% with . By contrast, commit guidelines enforcing tools such as SonarQube, CheckStyle, PMD, FindBugs, and unit-test thresholds showed a positive but non-significant difference of approximately 3.9% (0) (Digkas et al., 2020). The literature therefore presents Clean as You Code not only as a coding style but as a governance mechanism: monitor new-code density, set quality gates in CI, and prevent software decay by ensuring that the inflow of code is cleaner than the installed base.
This perspective complicates the common assumption that cleanup is mainly debt repayment. The results indicate that refactoring of modified methods remains essential, but cleaner new code is itself a major driver of downward movement in system debt density (Digkas et al., 2020). A plausible implication is that organizations can alter long-run codebase quality by controlling entry conditions for new code, even when legacy debt remains substantial.
4. Static analysis, linting, and continuous feedback
A tool-centric interpretation of Clean as You Code centers on immediate static-analysis feedback. In block-based programming, LitterBox operationalizes this idea for Scratch 3.0 projects. It accepts a local .sb3, project.json, or Scratch project ID; parses the program into an AST; constructs control-flow and data-flow structures; runs issue finders over the AST and CFG; and emits reports in JSON, CSV, annotated .sb3, LeILA translation, or console format (Fraser et al., 2021). The linter reports the sprite and script in which an issue occurs, highlights the exact blocks, and attaches a textual hint explaining the underlying reason and possible misconception.
LitterBox 1.5 implements four categories of finders: 9 syntax-error finders, 7 Scratch-specific bug finders, 23 general bug finders, and approximately 30 code-smell finders. Examples include “Call Without Definition,” “Missing Termination Condition,” “Missing Resource,” “Comparing Literals,” “Busy Waiting,” “Duplicated Script,” and “Long Script.” The system uses visitor-based pattern matching for local checks and CFG/data-flow analysis for global checks such as missing initialization or recursion without exit conditions (Fraser et al., 2021). Its hints are internationalized through Java ResourceBundles and can explicitly address conceptual misunderstandings, thereby tying cleanliness to pedagogy rather than only to maintainability.
Empirically, LitterBox was evaluated on 74,830 public, non-remix Scratch 3.0 projects, finding 109,951 total instances of the 25 bug patterns available at the time. Manual inspection of a stratified random sample of 250 reported bug instances yielded 32 false positives, for precision approximately 87.2% (Fraser et al., 2021). In this domain, Clean as You Code thus means real-time identification of both defects and smells, precise localization, and context-sensitive explanations that support correction while the learner is still within the relevant control-flow context.
For conventional textual languages, static-analysis enforcement also appears in studies of code smells and linter configuration. An empirical study of 31,687 Java files from 677 GitHub repositories examined 151 CheckStyle smells and asked which alerts are potentially causal for quality or productivity outcomes. Fewer than 20% of the smells were found to be potentially causal, and only approximately 3% were classified as robust after predictive, monotonicity, co-change, developer-controlled, and file-length-controlled checks (Amit et al., 2021). The strongest smells concerned simplicity, defensive programming, and abstraction, and files without the potentially causal smells were reported as 50% more likely to be of high quality. This evidence suggests that Clean as You Code is not equivalent to chasing every warning; its effectiveness depends on discriminating among alerts.
Configuration itself can be automated. LintCFG introduces a DSL-driven compilation pipeline that turns natural-language coding standards into linter configurations through five steps: NL-to-DSL parsing, configuration-name selection, option configuration, alignment checking, and rendering to a tool-specific format such as Checkstyle XML or ESLint JSON (Zhang et al., 8 Feb 2026). On Google Java plus Checkstyle, DSL representation achieved 89.7% accuracy, 96.2% precision, 100% recall, and 98.0% F1 for the Java guide, while config generation at the config-name level achieved 73.5% accuracy, 81.3% precision, 82.4% recall, and 81.9% F1. In a user study with 14 developers, the group with LintCFG reference configurations reached 95.2% correctness for config names, option names, and option values, versus 45.2%, 33.3%, and 23.8% respectively for manual-only participants, and completed tasks faster (Zhang et al., 8 Feb 2026). Here, Clean as You Code extends beyond source code to the executable formalization of coding standards themselves.
5. Human practice, refactoring habits, and contested smell priorities
Survey evidence indicates broad practitioner endorsement of Clean Code principles. In a study of 39 practitioners, respondents expressed shared agreement with Clean Code principles and their potential benefits, and reported that clean code helps reading, understanding, reusing, and modifying code (Ljung et al., 2022). The same study reports that developers tend to write messy code to be refactored later, and that open-ended responses highlighted postponing proper naming, deep nesting, copy-paste duplication, overlong methods, and god classes as common messy-code behaviors.
The survey also described endorsed cleaning strategies: opportunistic refactoring under the Boy Scout Rule, Extract Method and Extract Class to reduce size, incremental renaming, writing or improving unit tests to refactor safely, using IDE refactoring tools such as IntelliJ and Eclipse, and running static analysis such as SonarQube or ESLint as a pre-commit gate (Ljung et al., 2022). This establishes a sociotechnical picture in which Clean as You Code depends not only on abstract principles but on workflow support, test scaffolding, and local repair rituals.
At the same time, empirical work on code smells warns against treating all smells as equally important. The CheckStyle-based causal study found a pronounced mismatch between developer behavior and measured impact: formatting and whitespace smells such as MethodParamPad, WhitespaceAround, and EmptyForInitializerPad were removed more often, whereas high-impact smells such as IllegalCatch, UnnecessaryParentheses, ParameterAssignment, NPathComplexity, and AvoidStaticImport had lower annual removal rates despite stronger associations with bug-fix probability or productivity proxies (Amit et al., 2021). The literature therefore challenges a simplistic reading of Clean as You Code as “fix every smell immediately.” A more precise interpretation is to prioritize the warnings with the strongest empirical connection to downstream quality and maintenance outcomes.
This tension also reframes common misconceptions. One misconception is that cleanliness is identical with surface formatting; the smell-causality results contradict that interpretation. Another is that cleanup must be deferred to a dedicated refactoring phase; the survey results indicate that practitioners often do defer, but the technical-debt and architectural studies indicate that prevention and incremental refactoring can materially alter long-term structure and density (Ljung et al., 2022, Digkas et al., 2020, Brown et al., 2021).
6. AI-era reinterpretations: coding agents, dataset quality, and automated cleaning
Recent work extends Clean as You Code from human maintainability to machine interaction. A controlled minimal-pair study constructed six repository pairs—three Java-heavy and three Python-heavy—that matched on architecture, dependencies, build and test suite, and externally observable behavior, but differed in SonarQube issue counts and cognitive-complexity density (Trivedi et al., 19 May 2026). Across 33 tasks and 660 trials with Claude Code, cleanliness did not change pass rate: the cleaner side had mean 1, the messier side had mean 2, for an absolute difference of 3 percentage points. However, operational behavior changed substantially: input tokens fell by 7.1%, output tokens by 8.5%, reasoning characters by 11.1%, and file revisits by 33.8% on cleaner code, with revisitation deltas across repositories ranging from 4 to 5 (Trivedi et al., 19 May 2026).
The interpretation offered there is that cleanliness improves navigational efficiency rather than task success. Cleaner code breaks large or duplicated methods into smaller named helpers, reduces revisitations, and lowers the amount of contextual reasoning needed to understand control flow (Trivedi et al., 19 May 2026). This suggests that, for coding agents, Clean as You Code affects computational cost and search behavior even when final correctness remains stable.
A second AI-oriented line concerns training-data quality. One study applies an LLM-assisted three-step transformation pipeline to existing Python programs: variable renaming, modularization and decomposition into smaller helper sub-functions, and insertion of natural-language plans, with functional equivalence checked by rerunning original tests and retrying failures up to five times (Jain et al., 2023). Fine-tuning CodeLLaMa-7B on modularized data improved APPS-Introductory Pass@1 from 18.7% to 22.7% and Code-Contests Pass@25 from 6.4% to 8.3%, and training on only 6 essentially matched the accuracy obtained from the full original dataset on APPS-Introductory (Jain et al., 2023). In this setting, cleanliness is a property of training examples that improves downstream generation accuracy and data efficiency.
A related study addresses code smells directly in model-training corpora through SmellCC, an LLM-based code-smell cleaning pipeline. SmellCC first detects ten common smells with SonarQube, including Commented Code, Dead Code, Self-assigned Variables, Identical Expressions, Return and Yield, Empty Nested Blocks, Naming Convention, Collapsible if Statements, High Cognitive Complexity, and Long Parameter List; it then refactors regions one smell at a time using DeepSeek-Coder-V2 with role prompting, chain-of-thought substeps, and few-shot examples (Xue et al., 16 Aug 2025). Corpus-level smell elimination reduced 203,180 instances to 17,075, or 91.6% cleaned, and on 50 Python repositories functional correctness after cleaning was 91.3% while 96.8% of smells were removed (Xue et al., 16 Aug 2025). Fine-tuning on the smell-cleaned dataset improved code completion and code search metrics for DeepSeek-V1, DeepSeek-V2, and Qwen-Coder, while also greatly reducing smells in model outputs.
These AI-oriented results broaden the meaning of Clean as You Code. Cleanliness is no longer only for human readers, reviewers, or maintainers; it shapes the token footprint, navigational overhead, and learned representations of autonomous agents and code models (Trivedi et al., 19 May 2026, Jain et al., 2023, Xue et al., 16 Aug 2025). A plausible implication is that code-quality practices and model-quality practices are becoming partially coextensive, especially where live repositories also serve as future training data or agent operating environments.