Remember, One Class Per File

268 words.

Another in a series of random programming tips by Thomas Krehbiel, mostly to help me remember them in the future.

Here’s something I’ve recently learned on the endless journey to software development perfection: Don’t put more than one class/definition in a single source file.

I know, I know, many of you are saying, “duh.” Everybody has bad habits they have to overcome in life. :)

When I first started working with Java, the one-class-per-file rule annoyed me a lot. I hated having to make a whole source file just for a two-line class. It seems really wasteful. Then when I started working with C#, I loved being able to put related classes together into one source file. I was back in the comfort of my old C programming days. I could put a collection class and the element class in the same file! And just for good measure, I could add an enum and a delegate declaration. Life was good.

Time passed. One day, I went back to work on some old code, and I realized much to my horror that you can’t freakin’ find anything when you’ve got more than one class in a single source file! The reason for the one-class-per-file rule became abundantly clear: It makes code maintenance a lot easier. You can just peek over at the Solution Explorer and find the file you need. (I suppose I could use the Class Explorer, but I never do.)

So now I’m “refactoring” some old code files and splitting them into one class per file, like they should have been in the first place. Lesson learned.

Related

This page is a static archival copy of what was originally a WordPress post. It was converted from HTML to Markdown format before being built by Hugo. There may be formatting problems that I haven't addressed yet. There may be problems with missing or mangled images that I haven't fixed yet. There may have been comments on the original post, which I have archived, but I haven't quite worked out how to show them on the new site.

Sorry, new comments are disabled on older posts. This helps reduce spam. Active commenting almost always occurs within a day or two of new posts.