I want to figure out if its better to inherit a base class or interface or write the code up for entities. To better paint the picture assume the scenario below:
Scenario:
- There are 30 entities
- All entities have 2 common fields (createdDate, modifiedDate)
- 10 of the entities also have a extra field called serverStatus
What is the better way to code up these entities:
- Create base class with 2 common fields and have all 30 entities inherit it
- Do the above action (1) plus create interface that contains serverStatus and have the 10 entities inherit the interface as well
- Copy and paste the fields into each entity (including serverStatus in the 10 entities)
Thoughts as to proper way to approach this?
1 Answer 1
As always, keep it simple.
public abstract class EntityBase {
public DateTime CreatedDate { get; set; }
public DateTime ModifiedDate { get; set; }
}
public abstract class EntityWithStatus : EntityBase {
public int ServerStatus { get; set; }
}
Your concrete entity types can then derive from EntityBase
or EntityWithStatus
as appropriate.
answered Nov 4, 2017 at 8:42
-
So you saying for the 10 entities with extra field serverStatus i should just write the field in, and for all the 30 entities get them to inherit the EntityBase?Aeseir– Aeseir2017年11月04日 09:37:24 +00:00Commented Nov 4, 2017 at 9:37
-
No, not at all. The 10 entities with
ServerStatus
should inherit fromEntityWithStatus
, the 20 without should inherit directly fromEntityBase
. Never ever copy and paste code 10 times.Philip Kendall– Philip Kendall2017年11月04日 09:59:09 +00:00Commented Nov 4, 2017 at 9:59 -
Ahh i get ya. Can you add that little extra clarification into the answer for others to understand as well? I'll accept either way :)Aeseir– Aeseir2017年11月04日 10:00:54 +00:00Commented Nov 4, 2017 at 10:00
serverStatus
have to be an interface rather than another (probably abstract) class?