Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a bad practice to have multiple classes in the same file?

I used to have one class for one file. For example car.cs has the class car. But as I program more classes, I would like to add them to the same file. For example car.cs has the class car and the door class, etc.

My question is good for Java, C#, PHP or any other programming language. Should I try not having multiple classes in the same file or is it ok?

like image 638
Pokus Avatar asked Dec 11 '08 19:12

Pokus


People also ask

Can we have two classes in the same file?

Yes, it can. However, there can only be one public class per . java file, as public classes must have the same name as the source file. One Java file can consist of multiple classes with the restriction that only one of them can be public.

Should subclasses be in the same file?

You don't HAVE to, but generally speaking, yes. Keeping a subclass in the same file would be the exception to the rule. First of all, you shouldn't just pile tons of code into a single file.

Can you have 2 classes in a Python file?

In Python there is rule of one module=one file. In Python if you restrict yourself to one class per file (which in Python is not prohibited) you may end up with large number of small files – not easy to keep track. So depending on the scenario and convenience one can have one or more classes per file in Python.

Should each Python class be in its own file?

No. Typical Python style is to put related classes in the same module. It may be that a class ends up in a module of its own (especially if it's a large class), but it should not be a goal in its own right.


2 Answers

I think you should try to keep your code to 1 class per file.

I suggest this because it will be easier to find your class later. Also, it will work better with your source control system (if a file changes, then you know that a particular class has changed).

The only time I think it's correct to use more than one class per file is when you are using internal classes... but internal classes are inside another class, and thus can be left inside the same file. The inner classes roles are strongly related to the outer classes, so placing them in the same file is fine.

like image 57
Patrick Desjardins Avatar answered Oct 16 '22 23:10

Patrick Desjardins


In Java, one public class per file is the way the language works. A group of Java files can be collected into a package.

In Python, however, files are "modules", and typically have a number of closely related classes. A Python package is a directory, just like a Java package.

This gives Python an extra level of grouping between class and package.

There is no one right answer that is language-agnostic. It varies with the language.

like image 36
S.Lott Avatar answered Oct 17 '22 01:10

S.Lott