Reputation: 12821
Let's say I'm designing a Person class.
Is it appropriate to use an embedded class to group similar properties of this person?
For instance, let's a person has a weight, height, Hair color, and eye color.
Instead of hanging these properties directly off of the person, what if I created a class called PersonPhysicalAttibutes that had these properties.
So when you need to set a person's height, you'd use
personA.PhysicalAttributes.Height = 6.1;
Would you say this is a workable design?
EDIT:
One of the answers mention grouping address properties in a seperate class. I agree that that is a case where a seperate class works well. The address class could also be reused in an employer, customer or vendor class.
However I chose physical attributes as an example for a reason. My question is, does it make sense to break these out into another class when you're reasonable sure that that class won't be used in any other context? Strictly for ease of intellisense/grouping.
Upvotes: 2
Views: 67
Reputation: 4198
Not only is it appropriate, it's desired to split a big class into smaller classes. However, consider your naming. It would be most sensible to compose Person of objects like
Physique { Height, Weight, ... }
Face { EyeColor, HairColor, ... }
Psyche { Iq, Mood, ... }
Upvotes: 0
Reputation: 26
It depends on case to case basis. If you have group of properties such that all of them or most of them change together(in short the properties have strong binding in themselves), then it is appropriate to move them in another class. For example a person has address which contains houseNo,street,city,zipcode. These properties represent a group which can be associated with Person, but can exist together as a group. So including them in Person class would be inappropriate. Instead you should make a different class for them called Address and associate Address with Person. But weight,eyeColor, hairColor, height all of them are independent properties. Naturally they do not form a group together. It is better that they remain associated with Person class as an individual, independent properties. If you forcefully create a subgroup like the one you mentioned PhysicalAttributes, you will frequently come across a situation where you will violate law of Demeter.
Upvotes: 1
Reputation: 11495
This would be a violation of the Law of Demeter. In particular, by designing it this way, you are actually coupling the calling code to both your Person class and your PersonPhysicalAttributes class, thereby making later change to your code even harder.
I would avoid doing this approach, personally.
Upvotes: 0