Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there some Delphi specific issues with "One class per file" rule? [closed]

Old title: How many classes per unit are advisable to have?

My question is specific to Delphi. I think that in Java and C# world it is a rather accepted practice to generally have one file per class. I think this is a good rule to follow in Delphi too, because in Delphi private members aren't really private if you have more than one class in a unit.

So I was surprised to hear from two different senior (and probably more experienced than I am) programmers tell me I divide my code too much. One of them told me to not be shy about placing 5-6 classes in a unit.

Is there some issue with "one class per module" rule that I am not aware of, that could warrant and explain the reactions of these programmers?

like image 853
Escape Velocity Avatar asked Jul 21 '12 14:07

Escape Velocity


2 Answers

I don't know what you mean by module.

Java requires one public class per file, and the class name must match the file name. No ifs, ands, or buts. You can have other package private or private methods in that file, but only one public class.

If "module" means "package" to you, then I'd say it's common to have more than one class in a package. There's no norm; have a look at the JDK itself to see that. There are many classes in java.util, java.lang, java.sql, and javax.swing.

Besides those two, I have no idea what you or the alleged "senior programmers" are referring to. I would agree that it's possible to do anything to excess, and dogmatic rules should not be followed blindly.

But decomposition is a computer science -no, a problem solving - fundamental. It's more common to neglect it than to overdo it.

like image 73
duffymo Avatar answered Oct 05 '22 23:10

duffymo


It depends. There is no an exact rule to follow. Usually you need to grup classes in units by logical, common dependency or better to understand business functionality.

For example, if you have a lot of small helper, adiacent, complementary classes there is a reason to put all of them in a single unit. Like Borland did in DB.pas unit. All general DB stuff there: TDataSet, TDataSource, TField etc...

Forms, ie TForm descendants Borland recommends one per unit, because of dfm resource loading etc...

Usually when you write "uses FOO;" means that compiler include all stuff from FOO. You can access classes, consts, types etc... So, it's good to divide but keeping rationality.

In latest versions of Delphi units are treated as namespaces. You can better organize your code.

like image 24
Marcodor Avatar answered Oct 05 '22 23:10

Marcodor