Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantages to not splitting small(ish) classes into separate files?

Tags:

delphi

I have an "uObjects" unit. It has a several different types objects that extend TCollection/TCollectionItem. At one time having all these little bitty classes all grouped in one file probably made a ton of sense because things were small and they are kind of related and then you don't have a bajillion files to worry about.

But over time more and more methods have been added to some of these collections, making it harder to manage, so I'm thinking of breaking up the uObjects unit into multiple smaller units to make it more maintainable.

But before I do, I was wondering whether there are any caveats I should know about. Is this something I should go ahead and do without abandon? Or are there any reasons I might (perhaps in some cases) not want to break a unit's unrelated parts up into multiple units? Problems this could introduce down the road? I'm still trying to wrap my head around the nuances of Units, coming from the world of Java, where having multiple classes in a single file is not typically an option.

like image 902
Jessica Brown Avatar asked May 15 '14 04:05

Jessica Brown


1 Answers

The main issue is of circular dependency. Suppose you have these classes:

type
  TClass2 = class;

  TClass1 = class
    FObj1 = TClass2;
  end;

  TClass2 = class
    FObj2 = TClass1;
  end;

As written here, the circular dependency ties these classes to appear in the same file. That's because the circular dependency is only possible with a forward declaration. And forward declarations cannot apply across multiple files.

The other issue you may come across is private and protected member visibility. Within the same file, private and protected members defined in that file are always visible to other code in that file. This is a special exception to normal visibility rules that is a feature of Delphi.

When you move the classes to different files you might find that compilation fails due to private and protected members in other classes no longer being visible.

The Delphi idioms regarding class/file relationships differ in comparison to Java. Classes that work closely together are usually defined in the same file. On the other hand if class A exists fine without knowledge of class B then these two classes can usually be placed in different files.

like image 189
David Heffernan Avatar answered Nov 15 '22 06:11

David Heffernan