Back
Close

Modeling people and organizations - Party generalization

gpeipman
1,683 views

Party generalization

When modeling people and organizations we have to make generalizations that allow us to handle both of these as one when needed.

Imagine the case when customer can be either company or person. What happens if they are totally independent in data model? Let's see the bad scenario. Take a look at Invoice class and think if you want to see something like this in your data model.

public class Person
{
	public int Id { get; set; }
	public string FirstName { get; set; }
	public string LastName { get; set; }
}

public class Company
{
	public int Id { get; set; }
	public string Name { get; set; }
}

public class Invoice
{
	public int Id { get; set; }
	
	public Person CustomerPerson { get; set; }
	public Company CustomerCompany { get; set; }
}

Let's make things worse and imagine the whole data model where there are 60 classes that are related is with Person or Company but not both of these at same time. Horror, isn't it?

Party base class

Let's introduce Party base class that generalizes Person and Company. Demo below shows how to do it using class Party. Notice the DisplayName property that brings name of party to base class. Also notice how two invoices are created and for one of them customer is Person and for other Company.

using System;
public abstract class Party
{
public int Id { get; set; }
public abstract string DisplayName { get; }
}
public class Company : Party
{
public string Name { get; set; }
public override string DisplayName
{
get
{
return Name;
}
}
}
public class Person : Party
{
public string FirstName { get; set; }
public string LastName { get; set; }
public override string DisplayName
{
get
{
return FirstName + " " + LastName;
}
}
}
public class Project
{
public string CustomerName { get; set; }
public string Title { get; set; }
public DateTime Deadline { get; set; }
}
public class Invoice
{
public int Id { get; set; }
public Party Customer { get; set; }
// More members here ...
}
class Program
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

References

Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants