How to structure a small project so it doesn't turn into one giant file
Most beginner projects start as one file. That's fine, until it's 1,500 lines long and every change breaks something else. Here's how to grow structure gradually.
Signs it's time to split things up
- You scroll a lot to find anything
- Functions are long and do several jobs
- You copy and paste the same code in multiple places
- Changing one feature breaks an unrelated one
Steps that help
- Group related code. Put functions that deal with one thing (say, saving data or talking to an API) in their own file or module.
- Separate concerns. Keep user interface code, business logic and data access apart, even loosely.
- Extract small functions. If you can name a block of code, it can probably be a function.
- Move settings into config. Hard-coded paths and keys belong in one config place (and secrets in environment variables, not code).
- Add a clear entry point, such as
main.pyorindex.js, that wires pieces together.
A simple layout for many projects
src/for code, split into modulestests/for testsREADME.mdexplaining how to run it- A dependency file (
requirements.txt,package.json)
Avoid overdoing it
Don't create twenty folders for a 200-line program. Structure should solve a problem you actually have.
Bonus
Once code is split into small functions, writing tests becomes much easier.
How do you usually organize small projects? At what size do you start splitting files?
Comments · 4
Split by responsibility, not by type. Keep things that change together in the same module and name files by what they do.
Refactor when you feel pain, not before. Early over-structuring is as bad as the giant file.
How do you decide when a function or file is "too long"? Is there a rule of thumb?
No strict rule, but if you scroll a lot to understand one function or can't name what a file does in a sentence, split it.