Modeling people and organizations - Party generalization

gpeipman
1,168 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content