65 lines
2.2 KiB
Markdown
65 lines
2.2 KiB
Markdown
---
|
|
title: File Structure
|
|
tags: article software
|
|
created: 2023-07-28T09:21:24Z
|
|
published: true
|
|
---
|
|
|
|
There are two widely used types of source code organization and I will explain why one of these should be avoided.
|
|
As an example, let's take a look at the model-view-controller pattern:
|
|
|
|
## "by type"
|
|
|
|
An inexperienced programmer will often create this file structure when asked to create an MVC project:
|
|
|
|
```text
|
|
.
|
|
├── controllers
|
|
│ ├── Post.controller
|
|
│ └── User.controller
|
|
├── models
|
|
│ ├── Post.model
|
|
│ └── User.model
|
|
└── views
|
|
├── Post.view
|
|
└── User.view
|
|
```
|
|
|
|
We call this "by type" organization and it should be avoided like the devil.
|
|
|
|
First of all, it violates the software principle that related things should always stay close to each other.
|
|
It becomes very hard to find all the files related to a component.
|
|
Nowadays fuzzy finders can help offset this problem, but it's nonetheless a problem that could have been avoided in the first place instead of requiring extra tooling.
|
|
|
|
Secondly, this structure makes deletion non-trivial. If a component is no longer needed, then you need to delete it from your repository.
|
|
This should be a trivial task, ideally removing one directory and you're done. If your component, however, happens to be spread out over 15 different folders, then the deletion process is very complex.
|
|
|
|
## "by feature"
|
|
|
|
There is a very simple solution to all of these problems and it's called "by feature" organization:
|
|
|
|
```text
|
|
.
|
|
├── Post
|
|
│ ├── Post.controller
|
|
│ ├── Post.model
|
|
│ └── Post.view
|
|
└── User
|
|
├── User.controller
|
|
├── User.model
|
|
└── User.view
|
|
```
|
|
|
|
With this file structure:
|
|
|
|
- All related code is closely grouped together
|
|
- Deleting a component is very easy
|
|
|
|
Depending on the style regulations, you might encounter the plural forms `Posts` and `Users`, but it's the same principle. Personally, I prefer singular names because plurals aren't consistent. If your code uses type names via reflection to build the paths, you're better off with singular names.
|
|
|
|
## Conclusion
|
|
|
|
- Don't organize files by their file type
|
|
- Organize files by feature
|
|
- Make deletion simple
|