Nil Pun
Nil Pun

Reputation: 17383

Best practice or pattern for DTO/Domain Objects

I've a class below which is written to map with web service response message.

public class someclassA
{
   public int properyA {get;set;}
   public int properyB {get;set;}
   public int properyC {get;set;}
   public int properyD {get;set;}
}

public class someclassB
{
   public int properyX {get;set;}
   public int properyY {get;set;}
   public int properyZ {get;set;}
}

Now the requirement is that someClassA should use some properties from someClassB and add 3 more caculated properties e.g. propertyE, propertyF, propertyG etc.

The question regarding pattern is should I create completely different someClassAB to have all properties from someClassA and 3 new ones or should I just construct the someClassA with all those additinal field in the first place?

Cheers.

Upvotes: 1

Views: 895

Answers (1)

Jordan Parmer
Jordan Parmer

Reputation: 37224

Here is the rule to keep in mind. If A "is a" B, then use inheritance. Otherwise, make them separate objects. Inheritance should only be used in cases where the subclass is truly a more specific form of the parent class.

Think maintenance. What happens when the objects start to diverge more and more in the future? Now you have types being used where only say 20% of the properties make sense in a given context.

Not to mention, your code will be more readable if you have clear boundaries between unrelated entities. Every time you throw inheritance into the picture, you have one more "context" you have to keep up with when reading the code. If you mix objects (frankly out of laziness), the readability of the code suffers.

Upvotes: 2

Related Questions