Should one use self-referencing generic inheritance like Customer : Entity<Customer> - c#

Is it advisable to use self-referencing generic inheritance?
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 does one cast Customer to the base Entity class? What advantage does "Customer : Entity" provide? I see this kind of inheritance in examples showing NHibernate domain modeling.
Is it better to use "Customer : Entity" without the generics?

You should use it when you need it, not just because you can. In the example above, it makes some sense to implement Clone(). However, as you rightly point out, it means that your entity classes won't actually have a common base class, and properties that are truly common to them won't be accessible. The correct way to handle this is to split it in generic and non-generic 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, note the where part that I've added to declaration of Entity<T> - it ensures that this class can only be used as a part of this recursive pattern.

In the company i work for, the project I work on uses heavily this kind of trick. In fact, it is even promoted as a pattern in the code. Thus i can speak from experience: don't use it.
They may be cases where the self-referencing implementation is far simpler, more efficient and easier to read, but I have never encountered such a case. Heavy use of it makes code maintenance a nightmare, and in most cases can be avoided with only a normal inheritance and a casting of your method result if needed. And the performance cost of a casting into the derived class is negligible compared to the maintenance cost of your code.
So if you find the rare example where it is advisable to use self-referencing generic inheritance, go ahead and do so. But think twice beforehand, as there is probably a better way to do it.

Related

What is the practical usage of interface not directly implemented in class?

I think I have a very naive question here that I didn't knew before that it was even possible. Forgive me if my title question is a bit vague because I don't even know how to describe it. Here is the code that looks weird to me.
public interface IMyInterface
{
void ImplementMe();
}
public class StandAlone
{
public void ImplementMe()
{
Console.writeline("It works!");
}
}
public class SubClass : StandAlone, IMyInterface
{
// no need to implement IMyInterface here but it still work!!!
}
IMyInterface myInterface = new SubClass();
myInterface.ImplementMe(); // Output : "It works!"
I just want to know the following :
What is the right term to describe this approach?
What is the practical benefit of this kind of approach?
What kind of problem it tries to solve? or What scenario this will be applicable?
Well, first case that comes to my mind - when you don't own source code of StandAlone class, but later you decided to introduce interface which describes behavior of StandAlone class. E.g. for unit-testing (it's not best practice to mock code which you don't own, but sometimes it might be helpful) or you want to provide alternative implementation of StandAlone behavior in some cases. So either you have no options for unit-testing such code:
public class SUT
{
private readonly StandAlone dependency;
public SUT(StandAlone dependency)
{
this.dependency = dependency;
}
// ...
}
But if you'll introduce interface, you can actually switch to dependency from IMyInterface instead of StandAlone. And provide SubClass as implementation of interface with zero efforts.
public class SUT
{
private readonly IMyInterface dependency;
public SUT(IMyInterface dependency)
{
this.dependency = dependency;
}
// ...
}
But SubClass does implement the IMyInterface - it has all the required public members with the right signatures. There's no specific terminology since there's nothing weird about it.
In fact, some languages take this even further, and allow you to cast any object to an interface, as long as the class has the right members (and in yet more flexible languages, even if it doesn't).
The main benefit is again the same as any other way to use interfaces - it allows you to abstract the implementation away from the interface. It's just a shortcut to having to do an explicit interface implementation, something like:
class SubClass : BaseClass, IInterface
{
void IInterface.MyMethod()
{
base.MyMethod();
}
}
You might think that you could just implement the interface in the base class, but there's plenty of reasons why you wouldn't:
You don't want to maintain a public interface for the base class, it's just an internal class that shouldn't be exposed outside.
You don't have a way to change the base class to include the interface, so if you want to keep an inheritance chain, you must subclass and add the interface to the subclass.
The inferface contains some members that aren't contained in the BaseClass.
You'll probably find a couple more reasons if you try.
But the main point is: why not? You need a reason to do something (expand the definition of the base class instead of just the subclass). Adding abstraction everywhere along your codebase is rarely beneficial - you're trying to find a good trade-off between clarity of intent and clarity of implementation. An interface on a base class might help or hinder that.
One legitimate use of this pattern (Outside of simply the original programmer should have put the interface on the base class) could be that Standalone is in a 3rd party (or inaccessible) assembly, and IMyInterface was written in your own code to provide a Facade.
Consider this;
Your app wants to provide some functionality. You define an interface with method ImplementMe.
Standalone is in ThirdParty.dll and provides this exact method name (Perhaps you modelled your interface on that method name on purpose)
You subclass Standalone within your own code in order to implement your functionality.
Maybe you have a second way of implementing ImplementMe for which you have your onw class implementing your own interface. (public class MyOwnImplemetation : IMyInterface {... })
You could then use DI to instantiate the correct implementation of StandAlone or MyOwnImplemetation but treat them both as IMyInterface.
Not all classes are direct implementations of interfaces.
For example, let's put a good sample based on a simple class inheritance:
public class Person
{
public Guid Id { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
}
public class Employee : Person
{
}
Now, let's imagine that we need to store uniquely-identifiable objects in some common store where we don't care about the entities' types but just about they're uniquely-identifiable.
BTW, we consider that persons shouldn't be stored within such store, because they're not valid entities within our organization but they're just there to improve code reusability and don't repeat ourselves.
So we define an interface like this:
public interface ICanBeUniquelyIdentifiable
{
Guid Id { get; set; }
}
...and we don't implement it on Person but we do so on Employee:
// Now an employee is an actual object that can be uniquely identifiable,
// and this isn't true because Person has an Id property, but because
// Employee fulfills the contract!
public class Employee : Person, ICanBeUniquelyIdentifiable
{
}
Background
I would say that your reasoning should be that you implement interfaces where they really matter to be implemented, and reusability shouldn't be the key point when implementing interfaces.
Actually, you should implement interfaces on objects which should be accepted on some API and you just need a subset of the full type of a given object.

Inherit class minus some fields - possible workarounds?

I don't have access to the definition of a class but I can inherit from it. I want in the derived class to be denied from accessing some fields that are public in the base class for obvious reasons of accidentally accessing/setting/getting the fields/properties.
What choices do I have?
EDIT:
Why the downvote? I have to refactor a large code that was using the said inherited fields and I have to manually treat the lines involving not only those but also the chained inherited fields down the hierarchical tree.
Additionally I have to make sure even I or my partners won't access those fields/properties and still using those intentedly inherited.
EDIT:
A distinction must be made between 2 separate cases: when the programmer designs the application from ground up and when s/he is compelled to proceed from inaccessible code.
In the former case s/he is responsible for applying OOP and design patterns as best fit for the future intended use s/he envisions.
In the latter, situations often come up when the programmer needs to develop from a slightly modified proprietary given class to avoid unneeded complications for the long term. Often times the original code designer can't exhaust the use cases. Thus the developer makes a custom version of the class with the "promise" the original class won't be used and even if ever used, it will only be used for the purposes originally intended, and no inheritance or other relation exists with the new version. This new version would have additional members and other missing members as compared to the original class. This would be consistent with I in SOLID, albeit adapted for classes.
In these cases I admit that inheritance is not the way to go, as it has a different purpose and the developer would break L (and conceptually I) from SOLID by using inheritance. But there's no feature of any language that provides for this, so there's no choice left.
The way I see it, you need to use the Decorator/Wrapper design pattern. Instead of inherinting it, you wrap a class around it.
The class you have:
public class SealedPerson
{
public string Prop1 {get;set;}
public string Prop2 {get;set;}
}
The class you need:
public class SealedPersonWrapper
{
public SealedPersonWrapper(SealedPerson person)
{
this.Prop1 = person.Prop1;
}
public string Prop1 {get; private set;}
}
You can do this by separating interfaces:
public class BaseClass:IBase
{
private int A;
private int B;
void IBase.SetA()
{
A=10;
}
public void SetB()
{
B=10;
}
}
public class DerivedClass:BaseClass
{
public Set()
{
base.SetB();
//method SetA will not accessible through base class, but will accessible with IBase interface
}
}
Hide the inherited fields/properties/methods that you want unusable and make so using them would generate an error, like so:
public class Base // not owned code
{
public int free {get; set;};
public int limited {get; set;};
}
public class Derived:Base // owned code
{
// public new int limited; // NOT hidden! Still accessing Base.limited!
// working:
[Obsolete("Inaccessible hidden inherited variable", true)]
public new int limited {get; set;}
}
true is necessary to prohibit the compilation (trigger an error) instead of compiling with warning.
It's way much easier to write code especially for the unwanted fields than for the wanted ones, since using 90% of the base class.

How to write a good curiously recurring template pattern (CRTP) in C#

A while back I wanted to create my own data mapper that would be much simpler than your average ORM. In doing so I found the need to have access to the type information of inheriting classes in my base class. My first thought was reflection, but it's too slow (if you use reflection though, check out Fasterflect as it 'almost' eliminates the performance problems of reflection).
So I turned to a solution that I later found out had it's own name: The Curiously Recurring Template Pattern. This mostly solved my problem, but learning how to correctly implement this pattern was a little challenging. The two main questions I had to solve were:
1) How can I let my consuming code work with my generic objects without needing to know the generic parameters the objects were created with?
2) How can I inherit static fields in C#?
The challenging part was actually figuring out the questions. Once I realized what I needed to do, solving these questions was pretty easy. If you find yourself in need of the CRTP, you will likely find yourself needing to answer these questions... they seem to go hand in hand.
Working with generics without knowing the generic parameter types
When using the CRTP it's good to have a non-generic base class (abstract if possible, but that's not too important) that your 'base' generic class inherits from. Then you can make abstract (or virtual) functions on your non-generic base class and allow consuming code to work with your objects without having to know the generic parameters. For example:
abstract class NonGenBase
{
public abstract void Foo();
}
class GenBase<T>: NonGenBase
{
public override void Foo()
{
// Do something
}
}
Now consuming code that has no knowledge of what T is supposed to be can still call the Foo() procedure on your objects by treating them as instances of the base class.
How to solve the static field inheritance problem
When using the CRTP to solve a problem, it's often beneficial to provide access to static fields in inheriting classes. The problem is that C# doesn't allow inheriting classes to have access to those static fields, except through the type name... which often seems to defeat the purpose in this situation. You may not be able to think of a clear example of what I'm talking about and explaining one is beyond the scope of this answer, but the solution is simple so just tuck it away in your knowledgebase and when you find a need for it you'll be glad it's there :)
class GenBase<T>: NonGenBase
{
static object _someResource;
protected object SomeResource { get { return _someResource; } }
}
This 'simulates' inheritance of static fields. Keep in mind, however, that static fields on a generic class are not scoped across all your generic implementations. Each generic implementation has its own instance of the static field. If you want a single static field that is available to all the implementations, then you simply need to add it to your non-generic base class.
How can I inherit static fields in C#?
I know it's been a long time since you asked this, but, note that in the .NET 6 Preview, you can put static abstract members on an interface. (IIRC, this feature won't be in the release for .NET 6, it will be in preview status until .NET 7).
So, you can do something like this:
public interface IBoundedCollection
{
public static abstract int MaximumItemCount { get; }
}
public abstract class BaseCollection
{
public abstract int Count { get; }
public abstract int GetMaximumItemCount();
public abstract BaseCollection CreateUntypedCopy();
}
public abstract class BoundedCollection<TDerived> : BaseCollection
where TDerived : BoundedCollection<TDerived>, IBoundedCollection
{
public override int GetMaximumItemCount() => TDerived.MaximumItemCount;
public abstract TDerived CreateTypedCopy();
public override BaseCollection CreateUntypedCopy()
=> CreateTypedCopy();
}
public class LimitTenCollection : BoundedCollection<LimitTenCollection>, IBoundedCollection
{
public static int MaximumItemCount => 10;
public override int Count { get; }
public override LimitTenCollection CreateTypedCopy() => new LimitTenCollection();
}
Note the following:
You can work with BaseCollection without working with type arguments. For example, you can use Count, GetMaximumItemCount(), and CreateUntypedCopy().
BoundedCollection<TDerived> can provide the implementation for MaximumItemCount since TDerived is constrained to IBoundedCollection

I'm worried I'm adding too many interfaces

I am building out my domain model and continuing to refactor it. As I do, I am finding that I like interfaces as it allows me to create reusable methods/controllers/views for concrete types based on their interfaces. However, I am finding that I am creating an interface every time I add a new property to one of my domain entities.
For example, I have a MemberStatus object which inherits from an abstract Entity object which in turn implements the IIdentifiableEntity interface meaning that it has an Id property. MemberStatus also implements the INamedEntity interface meaning that it has a Name property, the IOrderedEntity interface meaning that it has a DisplayOrder property and the IHasMembers interface meaning that it has a collection Member objects. Here's the code:
public class MemberStatus : Entity, INamedEntity, IOrderedEntity, IHasMembers
{
public string Name { get; set; }
public float DisplayOrder { get; set; }
public ICollection<Member> Members { get; set; }
}
public abstract class Entity : IIdentifiableEntity
{
public int Id { get; set; }
}
public interface IIdentifiableEntity
{
int Id { get; set; }
}
public interface INamedEntity
{
string Name { get; set; }
}
public interface IOrderedEntity
{
float DisplayOrder { get; set; }
}
public interface IHasMembers
{
ICollection<Member> Members { get; set; }
}
Now, this seems to work fine as I other similar objects such as MemberPosition and MemberTeam which all implement these same interfaces and I can use my repository methods and controller actions with generics that implement these interfaces and have a lot of code reuse.
However, my concern is whether or not it's appropriate to keep adding simple, one-property interfaces every time I add a new property to my concrete objects. For example, let's say I want to add a bool Enabled property... should I continue to create a IEnabled interface? The reason I'm asking is that some of controller "initializers" that are using generics are becoming very long as shown in the following line of code. Is this normal and best-practice?
public abstract class OrderedCrudController<TEntity> : CrudController<TEntity> where TEntity : Entity, INamedEntity, IOrderedEntity, IHasMembers, new()
The fact that you are using interfaces is a good thing. However, you should ask yourself, if I create an IEnabled interface, will I ever reference my class by that interface alone? i.e. will there be contexts where I interact with my class purely via the single property that interface exposes?
Also, can you consider contexts where you will interact with multiple implementation of this IEnabled interface?
If the answer to both of these question is "no", then the interface serves very little purpose.
Having said that, please don't worry too much about this! it does very little harm.
Don't create interfaces that you don't foresee an imminent need for. Observe the YAGNI (you ain't gonna need it) principle. Otherwise you'll wind up with needlessly complicated code.
I think your problem is that you are trying to shoe-horn your domain model into whatever gui that you're displaying data in.
Instead, consider your domain object things that have behaviour close to data and in its c'tor, give it an Action<DomainEvent>. Now, make sure that you ONLY EVER pass data OUT from a domain object through this action.
Now, you listen. Whenever you actually want to make a change to your domain, call a method on it. Let your GUI be updated through the Action<DomainEvent> by taking these events and saving them to whatever read model that you are interested in.
Have a look at http://www.infoq.com/presentations/ddd-eric-evans and consider his points about domain events.
Now you don't have to add strange interfaces related to a technical domain into your business domain anymore. And remember; if you are doing CRUD like your examples show, then you are NOT doing domain driven design. You have an anemic domain.
Final point: use interfaces for things that actually need to be interchangeable. Are you carrying around a lot of INamed things in your application that can be interchanged with one another?
Let me also link this, for you to consider:
http://lostechies.com/jimmybogard/2011/10/11/event-sourcing-as-a-strategic-advantage/
http://lostechies.com/jimmybogard/2010/04/08/strengthening-your-domain-domain-events/

Creating a Namespace -> Class -> Nested Class? or

I was reading about creating classes and nested classes to determine what is the best approach for my needs, but I couldn't find something similar to what I need ( or couldn't understand it ;) ).
I will give you guys a (almost) real-life example:
Let's say I own a factory which manufactures different kinds of vehicles. So, my namespace would be Factory I figure.
Now, lets say the factory manufactures cars, boats and airplanes. So I will add three classes to my Factory namespace with those names.
Here is where my problem is with understanding the other methods:
I have some common things between the three types of vehicles. For example, they all have an engine (might be different HP or shapes which I understand are properties of the engine, but still they all have an engine). Also, cars and airplanes have doors (sometimes boats do too). On the other hand, they also have some unique things (airplanes have propellers for example that might come in different sizes or shapes).
Can someone please describe what I said in code so I could understand the differences between them?
Your question is a bit vague. Rather than try to answer it, I'll answer two related questions.
What is the purpose of a namespace?
The primary purpose of a namespace is to organize type declarations into a hierarchy so that they can be found by users easily.
The secondary purpose of a namespace is to provide a mechanism for disambiguating name collisions. That is, if XYZ Corp has a type Vehicle and ABC Inc has a type Vehicle, and PQR Ltd wants to use code from XYZ and ABC at the same time, the PQR programmers need a way to tell the compiler which type "Vehicle" actually refers to.
You suggest naming your namespace "Factory". That's probably a bad idea. A factory is probably a class, not a namespace. A factory is a kind of thing, not a way of organizing things. I would be inclined to name my namespace "Dementic.Manufacturing" and have it contain a Factory class. Now things are organized in two ways: first, by the company, Dementic Incorporated, that is producing the code, and by what the code is related to, namely, manufacturing. And it is unlikely that any competitor of yours will also make a namespace called Dementic.Manufacturing.
When should I make a nested type as opposed to a top-level type?
Make a nested type when the nested type is an implementation detail of the outer type. It is generally considered a poor practice to make a public nested type, though it is occasionally done.
A common example is an enumerator class; it is usually a private implementation detail of a enumerable collection.
You could stick all these in your Factory namespace.
A vehicle class would contain shared components, and classes for your specific vehicle types would inherit from the vehicle class... is that what you're asking?
public class Engine
{
public int HorsePower {get;set;}
}
public class Vehicle
{
public Vehicle() { }
public Engine Engine;
public int Doors;
}
public class Airplane : Vehicle
{
public Airplane () { }
public string PropellerModel;
}
public class Boat : Vehicle
{
public Boat () { }
public string RudderModel;
}
If you want to be as generic as possible, you can approach it something like this:
namespace Factory
{
public interface IDoor { }
public interface IEngine { }
public interface IPropeller { }
public abstract class Vehicle
{
public ICollection<IDoor> Doors { get; protected set; }
public ICollection<IEngine> Engines { get; protected set; }
}
public class Airplane : Vehicle
{
public ICollection<IPropeller> Propellers { get; protected set; }
}
}
Then have the specific concrete types provide the relevant collections to the supertype properties.
This is a bit of a hack, but modeling any real-world objects as classes in a programming language is going to break down sooner or later.
Note that I've made the engine property a collection too. This is to support, for example, the Prius class, which would have two engines.
An alternate approach would be to define the vehicles in terms of interfaces, somewhat like this:
namespace Factory
{
public interface IDoor { }
public interface IEngine { }
public interface IPropeller { }
public interface IDoorProvider
{
ICollection<IDoor> Doors { get; }
}
public interface IEngineProvider
{
ICollection<IEngine> Engines { get; }
}
public interface IPropellerProvider
{
ICollection<IPropeller> Propellers { get; }
}
public abstract class Vehicle { }
public class Car : Vehicle, IDoorProvider, IEngineProvider
{
public ICollection<IDoor> Doors { get; protected set; }
public ICollection<IEngine> Engines { get; protected set; }
}
// And so on...
}
This approach has the advantage that you don't have to define much on Vehicle itself, but this also means that you can't easily share the definitions of these members across all of the classes. However, this prevents you from defining members on the base type that are not relevant to the concrete types.
You have the wrong concept of what namespaces are. Namespaces have nothing to do with this.
I think you're also confusing inheritance and factories. Again, those are very separate ideas.
First think about creating your class heirarchy with the common base class that provides the basic structure of your objects and then the specialized subclasses that provide the specific details. And be careful not to use inheritance unless it truly works. Don't force your model into an inheritance heirarchy if it doesn't make sense.
Then you can worry about creating one or more factories to create instances of these objects.
As for namespaces, a namespace is just a way to group related pieces of code together in a logical, meaningful way. You might have a factory namespace, but you could just as well have a "factories" namespace or a "vehicles" namespace or something completely different which is relevant to your domain.
Since the person asking the question might actually get some value out of it, here my take:
If your software deals in some ways with objects of the real world, don't try to model the set of classes that represent the core of your application according to the real world. Rather, let the requirements of the software guide as to how your objects will look like.
For example, is this an order management system?
In that case it may be more relevant that certain orderable items have other orderable items directly associated with it. For a boat you can order certain parts, engines, etc. That is, it may more important to express the relationships between orderable items instead of having them available as concrete types.
For example, is it a tool to draw new boats, planes, propellers, etc.? Then a more relevant base class maybe that of a shape. Is it more about calculating the power of an engine or the efficiency of a propeller? Then you may need some concept of mathematical bodies and additional physical relationships and characteristics need to be defined between the different objects.
Lastly, as a rule of thumb you can think of inheritance as a somewhat overrated concept in that it is the first thing that starters think of when touching OO. The predominant concept of reuse in nature is composition - ultimately all natural things are composed of small items with very clear interfaces. Ideally, you will try and compose your OO application in a similar fashion.
I would rather go for VehicleFactory namespace, Factory as a class (there are many design patterns addresing the problem of creating objects and usually this needs to be a class, or at least (usually in non-objective programming) function. Namespace won't provide you this.

Categories

Resources