跪拜 Guibai
← Back to the summary

Move the Files Before You Touch the Architecture

Core conclusion: Most cases of "the project keeps getting messier" aren't wrong architecture, they're wrong ownership: files for the same feature get split across four type-based directories controllers/, services/, models/, utils/. Changing architecture means touching interfaces and dependency directions, which has a large regression surface; changing directories is just moving files, and a broken import fails immediately, with the machine as your safety net. So the order should be: move directories first, then talk architecture. This post gives three criteria for judging which camp you're in, a directly runnable directory audit script, and a controlled 16-file comparison: after the same feature scattered across 3 directories becomes 1 directory, cross-directory imports drop from 12 to 4.

📦 Companion resource: Directory audit script structure_audit.py (with --demo comparison samples, one command reproduces the numbers in this post)

Contents

1. One-sentence conclusion

The typical symptom of a messy project is "to change one feature, you jump between four folders". At that point the most natural reaction is "the architecture is bad, rewrite it" 🎭 — but nine times out of ten, all you need is to move the files of one feature into the same folder.

First, separate two things:

The two influence each other, but they are not the same thing. And they fail in completely different ways:

Action What happens if you get it wrong Who discovers it
Architecture rewrite Interface semantics silently shift, blows up at release Users
Directory rearrangement import immediately can't find the module, tests go red immediately Compiler and tests

Doing the thing whose failure is visible first is the most economical order in engineering. The three criteria below are there to confirm which side you're on.

2. Why "messy" usually isn't an architecture problem

Type-based layering (Package by Layer) is very comfortable in small projects: controllers/ for entry points, services/ for logic, models/ for entities, utils/ for utilities. Only after a project grows to dozens of features does its cost start to show: every new feature means stuffing a file into each of the four directories.

So the "order" feature is actually made up of four files in four directories, and nothing anywhere records that fact.

An analogy 🧺: your wardrobe is divided by "material" drawers: cotton, wool, synthetic. Sounds organized, but when you head out for a run in the morning you have to open the cotton drawer for the T-shirt, the synthetic drawer for quick-dry pants, then go to the entrance for socks. When the classification dimension is wrong, the neater the drawers, the slower the search. Organizing by occasion (work / sports / travel) is completely different: open one drawer and a whole set is there.

The key judgment: you don't need a new wardrobe, you need to change how you divide the drawers. Changing drawers doesn't require breaking down walls; that's the difference between "changing directories" and "changing architecture".

Conversely, when is architecture genuinely broken? When "orders" and "payments" share one piece of mutable global state, or two modules import each other forming a cycle. In those cases moving files won't save you, because the problem isn't location, it's dependency direction. Section 3 gives a decidable boundary.

3. Three criteria: move files or change architecture

Don't judge "messiness" by feel. Use three questions you can answer on the spot:

Criterion ①: Can you say in one sentence which files make up this feature? If you can't, or the answer includes "there's probably also something in utils…", it's an ownership problem: files are scattered, and no directory represents this feature. That's a directory problem; moving files cures it.

Criterion ②: How many sibling directories do you open to change this one feature? Opening 1–2 is normal; steadily 3 or more means the feature has been split apart. This is the most intuitive one, countable by hand.

Criterion ③: Is the share of cross-directory imports among all imports high? References inside the same feature shouldn't cross directories. Leave this one to the script in section 5 to count, don't guess.

Conversely, if any of the following appears, architecture is genuinely what needs changing:

Symptom Nature What to do
Two models with inconsistent fields for the same "order" Duplicated concept, boundary undefined Change architecture: unify the model and ownership first
Module A imports B, B also imports A Dependency cycle Change architecture: extract a middle layer or invert the dependency
Two features write to one shared mutable global state Implicit coupling Change architecture: make interfaces or events explicit
Feature files scattered across 3+ directories Unclear ownership Moving directories is enough
One directory holds 20+ unrelated files Classification dimension has failed Moving directories is enough

One-sentence rule of thumb: if the problem is "who depends on whom", change architecture; if the problem is "where files live", move directories. The former is a load-bearing wall, the latter is furniture placement.

4. Where the mess is: four countable metrics

The audit counts four quantities, all output by the script in section 5:

  1. Feature spread across directories: how many different directories contain files whose names include a feature keyword (e.g. order). This is the primary metric; 1 is best, 3+ means it should be consolidated.
  2. Cross-directory import count: one count for each source file that references a module outside its own directory. The bigger the number, the more times you cross directories to read one feature.
  3. Maximum directory depth: which level the deepest source file sits at. Depth itself is not a problem: feature-sliced layouts are usually one level deeper (features/order/service.py), but they're more concentrated. Depth must be read together with metric 1; reading it alone misleads.
  4. Extremes of file count per directory: how many files any directory holds. Above 20 with varied subjects, the directory has lost its classifying power and become a junk drawer.

What the four have in common: no code reading required, one os.walk pass computes them all. That's also their value: when discussing "should we refactor", the fear is everyone arguing from gut feel; turn it into four numbers and the debate immediately converges on "which one to fix first".

5. Complete runnable script: audit four metrics in one pass

Save the following as audit.py, run python audit.py . order from the project root. The second argument is the feature keyword you want to count.

"""Directory audit: count feature spread, cross-directory imports, max depth, and file count per directory."""
import os
import re
import sys
from collections import Counter

SKIP = {".git", "node_modules", "dist", "__pycache__", ".venv"}          # directories skipped during audit
IMPORT_RE = re.compile(r"^\s*(?:from|import)\s+([\w\.]+)")               # capture module path of an import


def collect(root):
    """Walk the directory tree, return (file relative path, containing directory) pairs, skipping dependency and cache directories."""
    out = []                                                            # collected results
    for cur, dirs, names in os.walk(root):                              # walk down level by level
        dirs[:] = [d for d in dirs if d not in SKIP]                    # filter ignored directories in place
        for n in sorted(names):                                         # fixed order for reproducibility
            if n.endswith((".py", ".js", ".ts", ".jsx", ".tsx")):       # source files only
                rel = os.path.relpath(os.path.join(cur, n), root).replace("\\", "/")
                out.append((rel, os.path.dirname(rel)))                 # record file and its directory
    return out


def main():
    """Output four metrics: feature spread, cross-directory imports, max depth, files per directory."""
    root = sys.argv[1] if len(sys.argv) > 1 else "."                    # directory to audit
    key = sys.argv[2] if len(sys.argv) > 2 else "order"                 # feature keyword
    files = collect(root)                                               # all source files
    hit = [(r, d) for r, d in files if key in r.lower()]                # files matching the feature keyword
    spread = len({d for _, d in hit})                                   # how many directories the feature spans

    dirs = {d for _, d in files}                                        # set of all directories
    cross = 0                                                           # cross-directory reference count
    for rel, _ in files:                                                # parse imports file by file
        if not rel.endswith(".py"):                                     # parse Python only for reproducibility
            continue
        for mod in IMPORT_RE.findall(open(os.path.join(root, rel), encoding="utf-8").read()):
            cand = mod.replace(".", "/")                                # module path to directory form
            if any(d and (cand + "/").startswith(d.split("/")[-1] + "/") for d in dirs):
                cross += 1                                              # counts when it hits another directory

    depth = max((d.count("/") + (1 if d else 0) for _, d in files), default=0)
    top = Counter(d for _, d in files).most_common(3)                    # three directories with most files

    print(f"Feature {key}: {len(hit)} files, scattered across {spread} directories")        # primary metric
    print(f"Cross-directory imports: {cross}")                           # coupling metric
    print(f"Max depth: {depth} levels / {len(files)} source files")       # structure metric
    for d, n in top:                                                    # most crowded directories
        print(f"  {d or '(root)'}: {n} files")


if __name__ == "__main__":
    main()

The script deliberately avoids "smart suggestions": it only converts gut feel into numbers. Judging whether to move, and which thing to move first, still falls to you: that part the machine can't replace, and shouldn't.

6. Controlled comparison: two directory layouts for the same code

The full script in the companion resource has a --demo mode that generates two comparison samples of 16 files each on the spot: one layered by type (controllers/ + services/ + models/ + utils/), one sliced by feature (features/{order,user,pay,report}/ + shared/). The two layouts have exactly the same number of features, files, and dependencies; only the directory organization differs.

Actual output from running python structure_audit.py --demo:

Metric By type (layered) By feature (sliced) Delta
Source files 16 16 0
Directories 4 5 +1
order files 3 3 0
order spread across directories 3 1 −2
Cross-directory imports 12 4 −8
Max directory depth 1 2 +1

Three readings that must be made clear:

  1. Not a single file disappeared; only positions changed. 16 vs 16, 3 vs 3: this isn't "tidiness saved by deleting code", it's purely ownership adjustment. So it carries almost no regression risk.
  2. Cross-directory imports dropped by 8, a 67% reduction. In the layered version every service imports models/ and utils/, and every controller imports services/; the sliced version has only 4 shared-tool references left (each feature imports shared/money once). The 8 removed references are the 8 directory hops AI makes every time it reads this feature.
  3. The sliced version is one level deeper. This needs a dedicated explanation, because it's easily misread as "slicing is messier". Depth goes from 1 level to 2, but feature spread goes from 3 directories to 1. Depth is position; scatteredness is distance traveled — fewer routes means genuinely less walking.

Statement of provenance: these numbers come from comparison samples generated on the spot by the script, not from any real commercial repo; you can reproduce them as-is with --demo, or run the same script against your own directories. The samples are synthetic, but the metric definitions and code logic are the same set.

7. Five-step progressive rearrangement: no big bang

Once you know what to move, the easiest mistake is "open a branch over the weekend and move every directory at once" — that gets you a 3,000-line diff nobody dares review and nobody knows where the gaps are. The right approach is to let the new structure grow itself:

Step 1: create directories only, don't move files. First add a features/ (or modules/), write a README stating the rule: new features always go into features/<feature name>/. Old code stays put; from today the codebase stops getting messier.

Step 2: move on touch. Set a team rule: whichever file this task touches, move that file's entire feature over to features/ as you work. Move the whole feature, not single files, or you'll end up in the worse state of "half a feature in the new directory, half in the old".

Step 3: move one feature at a time, use git mv. Preserve file history so git log --follow can trace it when something goes wrong. Don't both move and change content in the same commit — with two changes mixed, no reviewer can tell what you actually did.

Step 4: run immediately after each move. This step is the biggest advantage of directory rearrangement: a missed import errors on the spot, tests go red on the spot. Making "run tests immediately after a move" a hard rule turns one high-risk refactor into dozens of zero-risk small moves.

Step 5: move the next one two weeks later. Observe for a while and confirm there are no hidden path dependencies (build scripts, CI config, Docker mounts, IDE run configs are the ones most often missed), then move the second feature. At this pace, a mid-size project of dozens of features migrates naturally in two to three months, and stopping on any given day doesn't block a release.

This "move on touch, no big bang" approach has a recorded practice in the frontend community: create a features/ directory, put only new features in it, migrate old files as you encounter them, and the codebase completes migration naturally within six weeks, with no single large-scale refactor throughout.

8. In the AI era, directories are the retrieval index

This section is the real reason for "especially in the AI era": AI finds files by path semantics, not by your comments.

Human readers can lean on fuzzy memory: "that discount-calculating function, I think I saw it somewhere". AI has no such memory; the first thing it does when handed a task is glob and grep: locating candidate files by filename, by directory name, by keyword. This means:

That's also why putting a README in every folder for AI to read covers the other half of the same story: that post solves "how does AI know what this directory is for", this one solves "whether this directory should exist at all". Only with a sensible directory in place does a README have something to write about.

And the recorded practice of "move on touch, naturally migrated in six weeks" comes from the frontend directory-organization material below.

AI-era directory organization references (retrieved 2026-11-16):

And the conclusion in which programmers won't be eliminated in the AI era holds here too: AI made "writing code" cheap and made "being able to change it" expensive. Directory rearrangement happens to be the kind of change with the lowest cost and most direct benefit: it changes no behavior, only discoverability.

9. Troubleshooting table: symptom → cause → fix

Symptom Cause Fix
Opening four folders to change one feature Layered by type, feature split apart Create features/<feature>/, move the whole feature
New colleague can't find code after two weeks Directory names only name "layers", not "business" Rename directories to business nouns, demote layers to file suffixes
AI changes one spot and misses the other three Same feature's files not in the same directory Gather the feature first, then let AI work
One directory has 30+ files of everything Classification dimension failed, became a junk drawer Split into feature subdirectories, one at a time
A refactor takes two weeks and nobody dares review Big-bang migration Switch to move-on-touch, one feature at a time
Build script broke after a move Missed path references in CI / Docker / IDE Run the full pipeline immediately after moving, not just unit tests

10. Pre-release acceptance checklist

Move directories first, then talk architecture: as long as the problem is "where files live", the load-bearing wall isn't worth touching; only when dependencies form cycles or concepts duplicate does architecture come into play.

This column, 《AI 开发范式》(AI Development Paradigm), focuses on code organization, change cost, and collaboration style in the AI era. Every post comes with a directly runnable script or checklist, updated weekly. To read in order, subscribe on the column page.