I have 6 classes, which are all document types. All the document types have the same 8 fields. There is one class which consists of only these 8 fields. The rest of the classes have more fields. Some of these classes have the same fields (beside the 8 fields).
Example:
class Document: fields 1 to 8
class Form: fields 1 to 8 and field 9 and 10
class WorkInstruction: fields 1 to 8 and field 9 and 10
class Procedure: fields 1 to 10 and field 11
Hopefully this will make clear my point.
My question is, what is the best way to implement this? Should i make one or more interfaces, or should i use abstract classes?
Thnx
Either make Document the base type of Form etc, or make a form have the extra fields and a reference to a separate Document (i.e. use composition instead of inheritance). In this case it sounds like inheritance would quite possibly be the best option, but it really depends on what you want to do with it. Do you have code which is meant to work on any document, including Form, WorkInstruction etc?
EDIT: For example, suppose you have a user interface control which can show the common parts of any document – i.e. the common 8 fields. That would take an instance of Document. You may want to be able to pass a Form or WorkInstruction to it directly – in which case it’s best to derive from Document. Alternatively, when rendering a Form or WorkInstruction, you could create an instance of the control passing in the document part separately. i.e. it’s the difference between this (in C# – you haven’t specified which language you’re interested in):
and this:
Without knowing the rest of your design, it’s hard to recommend one or the other. I usually prefer composition over inheritance, but this feels like more of a natural inheritance situation.