Reputation: 1382
I have a "Package" table in database.
A Package can be of three types: Package A, Package B and Package C.
All the three package have some common fields like
1)name
2)size
3)weight
Now coming to the unique fields:
Package A & B must contain -
a)channel
Package C must contain -
a)completion
So, I create a table called as "Package" in database.
Columns of "Package" then would be:
1)id
2)type (1 = PackageA, 2 = PackageB, 3 = PackageC)
3)name
4)size
5)weight
6)channel (not required for Package C)
6)completion (not required for Package A & B)
So, I create an abstract class like below (ignoring datatypes of the properties):
public abstract class Package
{
public id;
public type;
public name;
public size;
public weight;
}
public class PackageA : Package
{
public channel;
}
public class PackageB : Package
{
public channel;
}
public class PackageC : Package
{
public completion;
}
what would I be doing wrong with this approach? Should the Package class be abstract or simply class?
Since I would not want other to work directly on Package class and instead take on Package A,B,C.
EDIT: What about the database part? Is it common to have fields/column like "channel"(needed for Package A & B) (not needed for Package C) and "completion"(needed for Package C)(not needed for Package A & B) to have "null" when not needed/used for specific package type?
Upvotes: 4
Views: 77
Reputation: 726579
The only thing that's wrong with this approach is that channel
is duplicated across PackageA
and PackageB
. You could fix it by adding another base class for the two package types that share a channel
:
public abstract class PackageWithChannel : Package {
public Channel Channel {get;set;}
}
public class PackageA : PackageWithChannel {
...
}
public class PackageB : PackageWithChannel {
...
}
This eliminates duplication of the Channel
property.
As for the database part, there are different ways of mapping a class hierarchy to an RDBMS, ranging from a single table for attribute-value lists to a table-per-hierarchy with a type field. You picked a table-per-hierarchy, which is entirely valid.
Upvotes: 2