Oct 212012
 
 October 21, 2012  Posted by at 11:30 pm Not So Stupid Questions  Add comments

[To celebrate my first year of programming I will ask a ‘stupid’ questions daily on my blog for a year, to make sure I learn at least 365 new things during my second year as a developer]

To group classes or not in files?

To group classes or not in files?

Finally, I had to ask this. Whenever I pop open a MSDN sample I see classes grouped under one file. I rarely do this, I do it while I’m trying things out, but move them out. Sometimes, just for illustration purposes when I write up examples, and its a rather small project, I will have the classes in the same file to make it easier to display the code in the blog entry. But I’ve seen this in quite a few ‘real life’ projects- and there might be a reason as to why?

On stackoverflow a few issues are discussed, such as checking in files – if you have multiple classes in a file it’s not that easy to spot what was changed. Another issue is that classes should be decoupled, and having them in one file signals that they are coupled, which they shouldn’t be- at the same time there are times when it is unavoidable to have coupled classes.

One user commented that he does sometimes do that when the classes are tightly coupled, but that it is a good rule not to. When asked why he has tightly coupled classes he answered: It’s called avoiding overengineering. If you have a few tightly coupled classes and decoupling them would add a lot of complexity compared to the amount of practical flexibility it provides, then what’s the point?

Quite interesting, and a fair comment I think. I’m curious if more devs have any thoughts on this? I’ve chosen to keep them separate , unless it’s just to illustrate something as I mentioned above.

  15 Responses to “Stupid Question 64: Is it considered bad practice to group classes under one file?”

  1. I have had to support some code in the past that I would describe as politely as possible as “not fit for purpose” and during such support I found that I really needed to read the change history of the file to get some clue as to why things were changed.
    (Usually stuff was changed due to customer feedback, but documenting change was not even a consideration).
    Where classes and other things were held in the same file it made reading the change history on a file extremely difficult and so for support purposes alone I would keep things in separate files where possible.

  2. Jimmy Nilsson once had a great illustration on the matter of thightly couple classes a few years ago.
    It was a picture of a soccer player and a football.
    He explained it like this; in this case it is good that the player is decoupled from the soccerball , you can swap out the ball with another one, or swap out a player.
    It would however be strange if the player was not tightly coupled to his own arms and legs, swapping out those makes no sense in this case.

    (maybe he didnt state it exactly like this, its what I recall here, but along those lines 😉 )

    And I think it is a really good way to think about it, sometimes there is no point in making things decoupled. mayne the classes work together as a whole.

  3. I group classes in very rare cases, like when a “parent” class is using a custom class (or subclass of something) for some very “one-off” kind of purpose. To me, that makes it clear nothing else should even be tempted to use that class, even if I put no actual “rules” in to enforce this. Should the need for that class ever arise anywhere else, I will move it out straight away.

  4. Awesome question 🙂

    I don’t think overengineering can be connected to this question. It’s like the confusion about how many projects a solution should contain – it will always be subjective opinion.

    Today I expect every class to be in it’s own file, whatever the condition. I use CTRL+SHIFT+T (file search) in Resharper a lot and actually expect I can find classes by filename.

  5. I always use one class / file, unless it’s a nested class (sometimes I use those).

    I don’t really see that you make things less engineered if you keep multiple class’ in a single file. It’s the number of class’ that determine complexity and not the number of files, right?

  6. If several classes are tightly coupled, it might make sense to refactor them into nested classes. Otherwise, one should follow the one class per file rule.

  7. Unless its a class that is only used internally to a parent class (very rare) then I vote to always use separate files. I have inherited a project with files pushing 15,000 lines (not fun)

  8. Even if they are tightly coupled you can organize them with a folder. Class per file is the standard in every refactoring tool. If you’ve ever given someone a really long code file, the first thing you will notice is they immediately scroll to the bottom and pretend they have read and understand the whole thing. Breaking classes into seperate files helps get a better “at a glance” picture of things. I dont think many will argue this isnt a best practice, but everyone chooses not to do it in certain situations.

  9. Cant even begin to think why you would use more than one.

    How can u hope to be productive having to search for things or wade thru hundreds of lines of code

    I think it shows poor design if more than one class jammed into a file

    Re the example of the soccer player and his arms , i don’t think thats a example of close coupling
    that is just the class “soccer player” he needs two arms n legs but not his own ball 🙂

  10. I guess if we were using Java then we would have no other choice. I think its fine in specific scenarios. The compiler probably doesn’t care a whole lot I suppose. Maybe a good practice if you must separate all classes into separate files is to group those files under a specific folder.

  11. This is a good question and one I have thrown around for years. I agree with Mark for finding things. As I know myself when I have put more than one class in a file, finding that class in the future can be a challenge. A challenge I can do without when I have an application in my head and I don’t want to push some of it out just to recall where the class is stored.

    One think I have been doing in my ASP.NET MVC applications is putting my view model classes at the bottom of the controller files. Probably not the best practice, but they are used with that controller and where they ended up. I guess a smarter place would be their own folder at the root level or under models. Like I said I have asked this question myself for some time. Sometimes I wonder if I think too much about code design and layout than just producing functionality.

  12. I see this as a source control concern. We want to store the classes in a manner that minimizes the volume of changes or classes touched when committing changes to source control. With multiple classes in a file, a change to any one of those classes in a file will mean that all classes are flagged as changed and rebuilt… not a good way to manage changes in a large project

  13. Hy iris
    Here I would answer it depends 😉 i always try to not have multiple classes in one file with two exceptions: syntax definitions for fluent interfaces or specs which belong together to a context. Especially when you have complex DSL it is helpful to have multiple classes in one file. Examples see here:

    https://github.com/danielmarbach/appccelerate/blob/master/source/Appccelerate.Bootstrapper/Syntax/ISyntax.cs

    Or

    https://github.com/danielmarbach/appccelerate/blob/master/source/Appccelerate.EvaluationEngine.Specification/HierarchicalEvaluationEnginesSpecification.cs

    Daniel

  14. If you put multiple classes in the same file it’s a nightmare to maintain.

    Here are my rules for this.

    1. Each class gets it’s own file
    2. Each class must be named the same as the file
    3. If you need 2 classes in a single file – consider making the secondary class a nested class inside the first
    4. All namespaces should match the physical folder structure

    By doing this – it’s a lot less confusing for new developers coming into a project.

    • And we even enforce this (except the special cases in my comment above) by applying stylecop rules to this.

      Daniel

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)

What is 11 + 14 ?
Please leave these two fields as-is:
IMPORTANT! To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)