Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class Design Question

Let's say I want to make a HumanBody class. And I want to store the length of each limb.

HumanBody.LeftArmLength = 14;
HumanBody.RightArmLength = 14.1;
HumanBody.LeftLegLength = 32;
HumanBody.RightLegLength = 31.9;

That's all well and good, but it seems like it would be better to do something like:

HumanBody.Arm.Left.Length = 14;
HumanBody.Arm.Right.Length = 14.1;
HumanBody.Leg.Left.Length = 32;
Humanbody.Leg.Right.Length = 31.9;

So this would involve making sub classes. Is what I'm describing something that is considered a "Good Practice"? It seems like this is a more organized way to store data.

Edit: this example is quite simple, but if there are 100 different pieces of data to store, this seems like a much better method to use.

like image 556
sooprise Avatar asked Nov 28 '22 19:11

sooprise


2 Answers

Left and right Arms are instances of Arm so perhaps:

HumanBody.LeftArm.Length = 14; 
HumanBody.RightArm.Length = 14.1; 
HumanBody.LeftLeg.Length = 32; 
Humanbody.RightLeg.Length = 31.9; 

Presumably, you need to consider cases where someone might not have both arms or legs.

[Note: As was noted in the comments, these should ideally be set in a constructor, rather than using properties. This is a general principle: Construct objects in a coherent, usable state.]

like image 198
Mitch Wheat Avatar answered Dec 10 '22 12:12

Mitch Wheat


It depends on the real situation. Here there doesn't seem to be very much point in grouping the two arms together and the two legs together... the concept of "a pair of arms" isn't generally a useful one.

On the other hand, if you were talking about grouping "DeliveryAddress1", "DeliveryAddress2", "DeliveryTown", "DeliveryZipCode", "BillingAddress1", "BillingAddress2", "BillingTown", and "BillingZipCode" into two instances of an Address class, that's a different matter.

Basically, do the individual parts belong together as part of a natural grouping? Is this group something you might want to handle in a composite manner? Could you see yourself passing the group to some other piece of code? If so, that sounds like a good unit of encapsulation. If not, maybe you're just complicating things unnecessarily...

like image 38
Jon Skeet Avatar answered Dec 10 '22 12:12

Jon Skeet