1

What is your opinion on multiple classes per file?

and having the filename not the same as the class
names?

Comments
  • 1
    I prefer one per file, unless the other classes are trivial and local to the main class
  • 2
    1 per file.

    Unless they're small extensions of the same class, then ok I guess.
  • 1
    Personally would like to keep it 1 class per file to keep things clean.

    At most might initialise enums if the class isn't static in the same file
  • 1
    I'm in this codebase where 44 classes where per file.. I'm just one month at this new company and I kinda want to clean this.. but have no Idea how to start on this strange task
  • 1
    I'm okay with it. While some languages enforce the 1-to-1 relationship (e.g. Java), some don't and instead use files as a kind of module (e.g. Python, Kotlin).

    In the end it's about understandability. If it helps to put multiple classes into a file, do it. If the file gets unwieldy, split it up.
  • 0
    Depends. I prefer one file per class but in Unity I often have a bunch of event definitions that vary only by argument types. I tend to throw those in a single file because use 4 lines per class tops.
  • 1
    In scala and ocaml, totally

    In java, no

    In rust, depends on the implementation
  • 1
    Don't be lazy, keep it clean for the next person.
  • 0
    It depends. For classes that differ greatly from each other, I think it's better to have them in separate files, but if you have a bunch of very short, very similar classes, it might be more helpful to group them in a single file.

    For example, one of my Python projects has a bunch of Enum classes all in a single file, but larger classes with methods get their own files.
  • 0
    @r3nrut which is cleaner, 294 files, each with a 20 line class, or one file, with all the boilerplate classes grouped?
  • 1
    @yellow-dog 294 files is cleaner if there’s a proper project, module and package structure.
  • 0
    @yellow-dog from a change control or devops perspective it's a lot easier to understand and manage change/risk. If you have 20 small classes in a file and you forget something in the one-liner code change that breaks everything in that file of classes, is this a risk your stakeholders are okay with? However, there is an argument to be made that if the classes in that file are related and utilizing inheritance properly, if there's a mistake they all break anyway.
  • 0
    @r3nrut do you not have tests?
  • 1
    1 per file. It makes the git history cleaner, reusability easier and testing less unwieldy.
  • 0
    @yellow-dog yup but like Almond Sauce pointed out... I don't want to maintain the tests for a giant file which a bunch of tiny classes. It's just setting someone up for a headache that seems so simple to solve by using a file per class.
Add Comment