Reputation: 17206
The title neds work, but the best explanation I can think of for the questions is an example.
Say you have an object "Note" that represents a note that can be attached to other types of objects in the system like Account, Appointment or something else. The notes only have a date and the content of the note, and can only be applied to one instance of another object.
So which is better:
Keep in mind that these are persistent classes, and I don't want to complicate things technologically by having subclassed Note types. I'd like to keep the domain as flat as possible in this instance.
Upvotes: 0
Views: 112
Reputation: 26668
So which is better:
- One type of Note that can have null references to the types it's not applied to (Note will have a reference to the appointment the note was made for, but null for the account/other objects in the system that it was not)
- Multiple Note types (AppointmentNote, AccountNote) which duplicates the same logic but avoids having irrelevent note references.
Neither. Also, I'm not entirely clear on whether we're talking about your objects or your tables.
Have one type of Note. It shouldn't reference the object it is related to at all.
public class Note
{
public DateTime CreatedAt { get; set; }
public string Content { get; set; }
}
public class Account
{
public ICollection<Notes> Notes { get; }
}
public class Appointment
{
public ICollection<Notes> Notes { get; }
}
Then there are a couple of ways to lay out the database tables, both of which should be easy to support with any ORM (though not necessarily easy to support with a not-really-an-ORM-but-half-looks-like-one, e.g. Linq2SQL or SubSonic, tools that generate a class per database table).
First DB layout:
TABLE Notes
(
Id,
CreatedOn,
Content,
AccountId,
AppointmentId
)
So what if n-1 foreign keys are null. This is table-per-class-heirarchy style and its accepted to have columns that are null and meaningless for certain subclasses.
Second method:
TABLE Notes
(
Id,
CreatedOn,
Content
)
TABLE AccountNotes
(
AccountId,
NoteId
)
TABLE AppointmentNotes
(
AppointmentId,
NoteId
)
And this would be more of a table-per-class layout. Nothing says you actually need subclassed Note types in code - but even if you were to do that, to avoid "fighting your tool," it doesn't imply duplication of logic - just use the base type and put your behavior there.
In the end, you're going to have to choose. Notes on appointments are intrinsically different from notes on accounts, you're going to have to deal with it on some level.
Upvotes: 2
Reputation: 219016
Why not just a single Note class which the other objects reference? Appointment, Account, etc. would just have a generic list of Note objects.
Upvotes: -1