In your object-oriented language, what guidelines do you follow for grouping classes into a single file? Do you always give each class a seperate file? Do you put tightly coupled classes together? Have you ever specified a couple of implementations of an interface in one file? Do you do it based on how many lines of code the implementation might be or how "cluttered" it might look to the user of the class? Or would the user prefer to have everything on one place?
No, while defining multiple classes in a single Java file you need to make sure that only one class among them is public. If you have more than one public classes a single file a compile-time error will be generated.
There is no limit on how many classes one can put in a file or a module.
So depending on the scenario and convenience one can have one or more classes per file in Python.
In C++ you can define multiple classes inside of a single file. You will not run into trouble by doing it. Would you elaborate "You will not run into trouble"? Your answer is opposite to the others.
Personally, I suggest one class per file unless the secondary classes are private to the primary class in the file. For example, a nested class in C# would remain in the parent classes file, but utility classes that might be useful elsewhere get broken into their own file or even namespace.
The key is to understand your environment and where people will look for things. If there is an established methodology in place, think carefully before you upset it. If your coworkers expect that related, tightly bound classes will be in a single document, having to search for them could be annoying (although with modern IDEs it shouldn't be a problem).
An additional reason for breaking things into more files rather than less is version control. If you make a small change, it should change only a small file where possible. If you make a sweeping change, it is obvious looking at the logs because of all the files (and indirectly, classes) that were affected are noted.
I think best practices in all OO languages I have ever used is to have one class in one file. I believe some languages may require this but I am not sure of that fact. But I would say that one class per file, and the name of the file matching the name of the class (as well as the directory structure matching the package structure for the most part) is best-practice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With