views:

209

answers:

3

SHould I create a separate class for each object in an aggregate or should the objects be nested classes of a single aggregate class?

+2  A: 

If the aggregated objects are separable, i.e., they may occur singly as well as in the aggregate, then I would have a separate class per object and use typed collections to represent the aggregates.

tvanfosson
+1  A: 

Not sure what MVC has to do with domain aggregates as it's possible to use the latter without a UI.

I generally prefer to make the parts of an aggregate separate classes because the parts can have business meaning on their own. Nested classes make sense when the outer class must be loaded before the inner class or when you cannot make the inner class public (at least these things apply to Java).

Alan
+2  A: 

It depends on how tightly coupled the object and the objects it contains are. If you have a Person class, and that person has zero-to-many Phone numbers, you'd generally want the PhoneNumber to be a separate class, because lots of different types of objects could have phone numbers (e.g. businesses, schools, etc). But if the object is something that's naturally tightly coupled, for example the Person object could have Toes, then an inner class may make sense.

Some questions you might want to ask yourself are: 1. Does the aggregated object require access to the private pieces of the containing class? If so, an inner class is a good bet. 2. Does the aggregated object always belong to exactly one object, and the object it belongs to never changes? If not, then you probably don't want an inner class. 3. Is the aggregated object meaningful outside of the context of the aggregating object? If so, it probably shouldn't be an inner class.

When in doubt, it's usually better to use a separately defined class, if for no other reasons that it keeps coupling down and your source files smaller.

Also not that it's not necessarily an either-or matter. You can always define a separate class or interface, and then subclass/implement it within the aggregating class.

Erik Engbrecht