If you use self-regulation of common inheritance, for example Customer: Entity <Customer>

Can self-regulation of common inheritance be used?

public abstract class Entity<T> { public Guid Id {get; set;} public int Version {get; set;} public T Clone() { ... // clone routine ... return T; } } public class Customer : Entity<Customer> { public string CustomerName {get; set;} ... } 

How to pour a client into an Entity base class? What advantage does "Client: Organization" provide? I see this inheritance in examples showing NHibernate domain models.

Is it better to use Client: Essence without generics?

+4
source share
2 answers

You should use it when you need it, and not just because you can. In the above example, it makes sense to implement Clone() . However, as you correctly noted, this means that your entity classes will not actually have a common base class, and properties that are really common to them will not be available. The right way to handle this is to split it into common and non-common parts:

 public abstract class Entity { public Guid Id {get; set;} public int Version {get; set;} } public abstract class Entity<T> : Entity where T : Entity<T> { public T Clone() { ... // clone routine ... return T; } } 

Also, pay attention to the where part that I added to the Entity<T> declaration - this ensures that this class can only be used as part of this recursive template.

+4
source

In the company I'm working on, the project I'm working on uses this trick a lot. In fact, it even advances as a pattern in code. Thus, I can speak from experience: do not use it.

They may be cases where the implementation of self-regulation is much simpler, more efficient, and easier to read, but I have never encountered such a case. Its intensive use makes the code a nightmare, and in most cases it can be avoided only with normal inheritance and bringing the result of your method, if necessary. And the cost of casting to a derived class is negligible compared to the cost of servicing your code.

So, if you find a rare example where it is advisable to use self-regulation of shared inheritance, go ahead and do it. But think twice in advance, as there is probably the best way to do this.

+3
source

All Articles