Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many classes should a programmer put in one file?

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?

like image 356
Doug T. Avatar asked Jan 22 '09 16:01

Doug T.


People also ask

Can we have multiple classes in single file?

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.

How many classes should be in a Python file?

There is no limit on how many classes one can put in a file or a module.

Can you have multiple classes in one Python file?

So depending on the scenario and convenience one can have one or more classes per file in Python.

Can you have multiple classes in one cpp file?

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.


2 Answers

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.

like image 155
Godeke Avatar answered Nov 16 '22 00:11

Godeke


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.

like image 24
Ryan Guill Avatar answered Nov 16 '22 01:11

Ryan Guill