I had this discussion many times over the last few years:
- Should we have a class per file?
- What about other types such as interfaces, enums, …?
Opinions on this subject vary a lot. This purpose of this article is to provide you some basic guidelines and why you should follow them.
Table of contents
- General guidelines
- Advantages of having one type per file
My guidelines are the following:
- Every public type (class, interface, …) should have its own file, no matter how small it is.
- Usually you’ll need only 1 file per type, but in some cases it’s OK to have partial classes (for example, one part of the class is generated by any tool).
- Regarding inner classes – I keep them in the same file of the class that uses them.
Advantages of having one type per file
1. Source Control
Having one type per file has the following advantages:
- You can easily see which types changed in one particular commit, without doing diffs
- It’s easier the see the history of a type
- You’ll have more files, so the probability of having 2 or more people working on the same file will be lower. This will reduce the probability of having conflicts and then doing mergings, which can be painful.
2. Finding Types
Having one type per file can also make your life easier when you’re trying to find a type definition. One may argue that you just need to press F12 (“Go To Definition“), but if you don’t have in front of you a piece of code that uses that type you’ll have to find it in another way:
- 2.1 Using Visual Studio
If your projects are properly organized it’s easy to find a type definition. All you need is to go to the Solution Explorer, then go the folder that corresponds to the type namespace and finally you’ll see the corresponding file:
- 2.2 Using DPack plugin
I used Dpack in the past, it’s freeware and one of my favourite functionalities is the File Browser, which allows you to easily locate files in the entire solution. All you need to do is to press Alt+U and start typing:
- 2.3 Using Resharper
If you’re using Resharper, you can press Ctrl+Shift+N (Go To File) and start typing and then you’ll see a list of files in the entire solution: