My application I have two types of customers: individuals and business customers. My users sometimes need to be able to see the full details of one customer, but at other times they only need to see a brief summary with a few fields (e.g. in a list of search results). I currently have three classes: IndividualCustomer
, BusinessCustomer
, and CustomerSummary
. These are plain old Java objects (aka POJOs) with getters and setters as their only methods.
I am contemplating whether to combine them using inheritance or possession. For example, maybe there should be a Customer
interface which they all implement. In that case, perhaps the interface requires the methods of CustomerSummary
so I can do away with that type. Or perhaps there should be a Customer
class with a few fields (like the current implementation of CustomerSummary
and it should "have a" BusinessCustomer
or IndividualCustomer
for the details.
The things that concern me are: if I make a Customer
interface and eliminate CustomerSummary
, then the types IndividualCustomer
/BusinessCustomer
will sometimes be only partially populated with details, having lots of null fields, and it would be a disaster if one of those "summaries" ended up hitting a .save()
method and overwriting real data with nulls. If I go with the possession approach where a Customer
object has a business or individual customer as a private field, then I have to do frequent type checks or type casts in order to be able to use the two types interchangeably.
What's the best design pattern for this kind of case, where an object is sometimes only partially populated (i.e. a "summary"), but can be populated with two different subtypes of details?