SHould I create a separate class for each object in an aggregate or should the objects be nested classes of a single aggregate class?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.