Bookmark and Share

One Public Type Per File

by KodefuGuru 30. June 2009 17:52

I remember when I started working on this particular project a few months ago. When I looked over the code for the first time, I noticed something funny about the cs files. Each cs file contained multiple public types. In the extreme cases, there were dozens of public classes in one file.

I brought it up with my new teammates, and one person claimed that he liked to keep related classes in a single file. I mentioned that I find it more difficult to find what I’m looking for in the solution tree, but he shrugged it off by suggesting I use the search feature.

Having never seen this type of code structure before, and with the knowledge that you group related classes by namespace, I decided to research why I felt so strongly that public types deserve their own file. I referred to the Framework Design Guidelines book by Krysztof Kwalina and Brad Abrahams (which is a great reference, btw). The first rule under A.4 File Organization is “DO NOT have more than one public type in a source file.” It then lists a few exceptions (number of generic parameters, nested, etc.).

Today I received yet another reminder of why this type of file structure is bad. I pulled down the latest code, then I retrieved a shelveset I was working on last week. I knew I might have to merge a few files, but I didn’t expect this.

DefinedMoreThanOnce

Ignoring the misspelled class name, someone had moved the type from a file I was working on to another. This kind of silliness wouldn’t happen if the class had its own file. I wasn’t even working on that particular class. As it turned out, the class in question was used by a few xaml pages, and a developer thought it fit better with a different xaml page than its original home.

My rule is one public type per file, using namespaces and project folders to group related types. This reduces the amount of potential editing conflicts and makes it easier to find the type in the Solution Explorer. If you have types with the same name but a different number of generic parameters, name the file by the class name with `(# generic parameters) at the end. For example, List<T> would be List`1.cs.

Tags:

Kodefu

blog comments powered by Disqus

KodefuGuru.GetInfo()

Chris Eargle
LinkedIn Twitter Technorati Facebook

Chris Eargle
C# MVP, INETA Community Champion


MVP - Visual C#

 

INETA Community Champions
Friend of RedGate
Telerik .NET Ninja
Community blogs & blog posts

I am a #52er

I have joined Anti-IF Campaign


World Map

Tag cloud

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010