Let say I have a class like this:
public sealed class Foo
{
public void Bar
{
// Do Bar Stuff
}
}
And I want to extend it to add something beyond what an extension method could do....My only option is composition:
public class SuperFoo
{
private Foo _internalFoo;
public SuperFoo()
{
_internalFoo = new Foo();
}
public void Bar()
{
_internalFoo.Bar();
}
public void Baz()
{
// Do Baz Stuff
}
}
While this works, it is a lot of work...however I still run into a problem:
public void AcceptsAFoo(Foo a)
I can pass in a Foo here, but not a super Foo, because C# has no idea that SuperFoo truly does qualify in the Liskov Substitution sense...This means that my extended class via composition is of very limited use.
So, the only way to fix it is to hope that the original API designers left an interface laying around:
public interface IFoo
{
public Bar();
}
public sealed class Foo : IFoo
{
// etc
}
Now, I can implement IFoo on SuperFoo (Which since SuperFoo already implements Foo, is just a matter of changing the signature).
public class SuperFoo : IFoo
And in the perfect world, the methods that consume Foo would consume IFoo's:
public void AcceptsAFoo(IFoo a)
Now, C# understands the relationship between SuperFoo and Foo due to the common interface and all is well.
The big problem is that .NET seals lots of classes that would occasionally be nice to extend, and they don't usually implement a common interface, so API methods that take a Foo would not accept a SuperFoo and you can't add an overload.
So, for all the composition fans out there....How do you get around this limitation?
The only thing I can think of is to expose the internal Foo publicly, so that you can pass it on occasion, but that seems messy.
I found myself asking that same question until I started working on reusable libraries of my own. Many times you wind up with certain classes that just cannot be extended without requiring obscure or arcane sequences of calls from the implementor.
When allowing your class to be extended, you have to ask: if a developer extends my class, and passes this new class to my library, can I transparently work with this new class? Can I work properly with this new class? Is this new class really going to behave the same?
I've found that most of the time the sealed classes in the .Net Framework have certain under-the-hood requirements that you aren't aware of, and that given the current implementation cannot be safely exposed to subclasses.
This doesn't exactly answer your question, but it provides insight as to why not all classes are inheritable in the .Net Framework (and why you should probably entertain sealing some of your classes too).
I'm afraid the short answer is, you can't without doing what is required, i.e. pass the composed instance variable instead.
You could allow an implicit or explicit cast to that type (whose implementation simply passed the composed instance) but this would, IMO be pretty evil.
sixlettervariable's answer is good and I won't rehash it but if you indicated which classes you wished you could extend we might be able to tell you why they prevented it.
Related
Assume this hypothetical situation:
I have a hierarchy of classes:
public class MyBase : System.Windows.Forms.TreeNode
{
public virtual void Init() {...}
}
Now I want to allow third parties to use MyBase to develop their derived classes like these:
public class Drv1 : MyBase { public override void Init() {...} }
public class Drv2 : MyBase { public override void Init() {...} }
I want my application be able to use Drv1 and Drv2 as plug-ins.
Now, my questions are:
Is it incorrect (or bad practice) to use classes (instead of interfaces) to set up plug-in mechanism?
Did I make a mistake I didn't use interfaces to provide THIRD-PARTIES with an interface? (because I want to persuade others to develop plug-ins for my app)
If answer of question 2 is YES, how could I use interfaces (because MyBase is derived from TreeNode) ? (this answer is critical for me)
Many thanks in advance.
Im using following rules:
If there is any code required in base then go for class.
If you need only structure or you need to "inherit" more than one class, use interfaces.
If you need both, features and multiple inheritance use both.
Its really depends what you do with that classes later on.
In your case you should be using base class as virtual method has some code in it, and you inherit from class that is 3rd party for you.
But once your business classes should use different implementation of that class then its worth of adding interfaces and use it in IoC or something.
I think going for Interfaces for only sake of it is not correct approach.
Is it incorrect (or bad practice) to use classes (instead of interfaces) to set up plug-in mechanism?
Neither C# or .NET has anything that labels this as incorrect. They describe under what circumstances your code will continue to work, and when it won't. Bad practice is a matter of opinion, but there are advantages and disadvantages to both approaches.
If answer of question 2 is YES, how could I use interfaces (because MyBase is derived from TreeNode) ? (this answer is critical for me)
If your callers need to provide a type that is derived from TreeNode, and you wish to use an interface, then you can.
public interface IMyInterface {
void Init() {...}
}
You cannot require classes implementing IMyInterface to derive from TreeNode, but you do not need to: you can ensure that the only way this gets exposed to your own application is via a generic registration method, where the generic type constraints do force the type to both derive from TreeNode and implement this interface:
public void RegisterTreeNode<T>() where T : TreeNode, IMyInterface {...}
If plugins are able to call RegisterTreeNode<Drv1>(), you're assured at compile time that it's going to match your requirements. You may of course use a different method signature, possibly one that deals with individual instances of the TreeNode class, it's the type constraints that are key here. If a caller attempts
class X : IMyInterface { public void Init() {...} }
and then
RegisterTreeNode<X>();
the compiler will simply reject this. The plugin may create instances of this X itself, but if your application never sees them, they cannot cause any harm.
Then third parties can do:
public class Drv1 : TreeNode, IMyInterface { ... }
public class Drv2 : TreeNode, IMyInterface { ... }
or even
public class Drv3 : SuperTreeNode, IMyInterface { ... }
where SuperTreeNode is derived from the standard TreeNode.
This is probably the main benefit of using an interface here: it's compatible with existing classes which provide additional functionality on top of the standard TreeNode.
This cuts both ways: the main benefit of using a common base class here, rather than an interface, would be that your own code can provide additional functionality.
P.S.: Depending on what you're after, it may also be possible to decouple this, to make your base class / interface responsible for creating TreeNode objects, rather than deriving from TreeNode. The general rule that favours this approach is called "composition over inheritance", and worth reading up on. It may or may not be a good fit for your particular use case.
I am aware that you should depend on abstractions not concrete implementations but I am also aware of the YAGNI principle. I sometimes find myself struggling to reconcile both of these.
Consider the following classes;
public class Foo
{
public void DoFoo()
{
}
//private foo stuff
}
public class Bar
{
private readonly Foo _foo;
public Bar()
{
_foo = new Foo();
}
}
"Bar" is the class I am interested in; obviously there is a problem, Bar is instantiating an instance of Foo, so let me refactor;
public class Bar
{
private readonly Foo _foo;
public Bar(Foo foo)
{
_foo = foo;
}
}
Great, but Bar's constructor still depends on Foo, a concrete implementation. I haven't gained anything (have I?). To fix this I need to make foo an abstraction and this is where my problem begins.
Every example I ever find always (understandably) demonstrates constructor injection using abstractions. I'm all for programming defensively but lets presume I have no need for any other implementations except Foo (test doubles don't count). To create an "IFoo" interface or a "FooBase" abstract class surely violates the YAGNI principle? I would be making something for a possible future scenario and I can always do that later e.g.
public abstract class Foo
{
public abstract void DoFoo();
//private foo stuff
}
public class Foo1:Foo
{
public override void DoFoo()
{
}
}
This doesn't break Bar and I could even do this for an interface provided I dropped the "I" convention (which I grow ever more sceptical of) e.g.
public interface Foo
{
void DoFoo();
}
public abstract class FooBase:Foo
{
public abstract void DoFoo();
//private foo stuff
}
public class Foo1:FooBase
{
public override void DoFoo()
{
}
}
What is wrong with injecting a concrete implementation since I can refactor this to an abstraction at a later stage (provided I give the abstraction the same name as the concrete implementation)?
Note: I am aware of the arguments for the "I" interface naming convention and this is not the point of my question. I am also aware that making Foo an abstract class will break the code wherever I was previously instantiating it, but presume I am using DI extensively and so I would only need to change the DI container registration, something I would probably have to do anyway if I were to introduce a new implementation of Foo.
but Bar's constructor still depends on Foo, a concrete implementation. I haven't gained anything (have I?).
What you gained here is that when the dependency Foo itself gets any dependencies of its own, or requires a different lifestyle, you can make this change without having to do sweeping changes throughout all consumers of Foo.
I have no need for any other implementations except Foo (test doubles don't count)
You can't just ignore unit testing in this. As Roy Osherove explained a long time ago, your test suite is another (equally important) consumer of your application with its own requirements. If adding the abstraction simplifies testing, you shouldn't need another reason for creating it.
To create an "IFoo" interface or a "FooBase" abstract class surely violates the YAGNI principle?
You won't violate YAGNI if you create this abstraction for testing. In that case YNI (You need it). By not creating the abstraction you you are optimizing locally within your production code. This is a local optimum instead of a global optimum, since this optimization doesn't take all the other (equally important) code that needs to be maintained (i.e. your test code) into consideration.
What is wrong with injecting a concrete implementation since I can refactor this to an abstraction
There isn't anything wrong per see to inject a concrete instance, although -as said- creating an abstraction could simplify testing. If it doesn't simplify testing and letting the consumer take a hard dependency on the implementation could be fine. But do note that depending on a concrete type can have its downsides. For instance, it becomes harder to replace it with a different instance (such as an interceptor or decorator) without having to make changes to the consumer(s). If this is not a problem, you might as well use the concrete type.
As adaam mentioned there is nothing wrong with doing what you want.
What DI Container are you using? If you are using Unity, PRISM has a pretty good example of how to register your ViewModels as BindableBase(Base class provided by PRISM) unless you have a base class that implements additional interfaces implemented.
Typically I have a BaseViewModel that extends BindableBase and implements INotifyDataErrorInfo and some otherinterfaces. Then when modules are being discovered, they register the ViewModels as types of BaseViewModel.
Providing Foo in constructor of Bar still gives you something compared to instantiating it inside Bar, even if just concrete implementaiton. Suppose you want to test your Bar, and suppose you designed Foo in a way that all functionality which might cause problems with unit testing is placed in virtual methods. Then in your unit test you inherit from Foo, override necessary members, and then pass instance of your inherited class to Bar constructor, which obviously would not be possible if you instantiated Foo inside Bar itself. Same story with DI - you can register class inherited from Foo as Foo in DI container.
I have an interesting problem that I keep circling around, but I never seem to quiet find a solution.
I tend to be a defensive programmer, so I try to write code that prevents problems from happening rather than reacting to problems once they've occurred. To that end, I have the following situation. Take the following code:
public class Base {}
public Interface IBase {}
public class Derived : Base, IBase {}
public class Derived2 : Base, IBase {}
...
public class DerivedN : Base, IBase {}
public class X : Base {}
public class Y : IBase {}
I need to pass a list of objects that derive from Base and implement IBase to a collection, and I need to make sure that only objects that have both are added to the list. Additionally, there can be an arbitrary number of classes that have both, so I cannot use the derived classes as constraints.
If I make the list of type Base, then I could add a Y object. If I make it of type IBase, then objects of type X can be added (neither of which are permitted).
I could, of course create my own generic collection class that has both types and has constraints for both. But, I don't want to have to do this for all possible collection types, and it's a lot of effort to duplicate all that functionality (even if you just forward the method calls to a contained class).
I could also create a BaseWithIBase class, which derives from both Base and IBase, and use that as my collection type, but I really don't want to force another abstraction if I don't have to.
I don't want this to be a runtime check, so walking the tree and throwing exceptions is not acceptable.
Can anyone suggest a better approach to this problem?
NOTE: Base and IBase are not related, just pointing out they are both base items of different types.
EDIT:
It seems that everyone wants to insist that "you don't need to do that" and that it's "not OOP". Nothing could be further from the truth. I was attempting to remove the specific from the question to prevent these kinds of questions and comments, so I will include my real situation.
The code is an implement of a Windows Service framework, based on the .NET Frameworks ServiceProcess.ServiceBase class. I am adding my own framework on top of this, that is intended to be heavily Dependency Injection based, and highly testable.
The collection must contain objects that derive from both ServiceBase and IService. IService is my framework extension that is used in my code, and for testing. It is basically just this:
public interface IService
{
void Start();
void Stop();
}
In addition, I have a number of other interfaces:
public interface IRestartableService
{
void Restart();
}
public interface IConfigurableService
{
void Configure();
}
etc.. etc.. and a service may look like this:
public class MyService : ServiceBase, IService, IConfigurableService {}
My code requires IService, Windows requires ServiceBase, thus both are needed because I work with IService, and windows works with ServiceBase. I only require IService, the other interfaces are optional.
You can create your own wrapper collection simply:
// TODO: Work out which collection interfaces you want to implement
public class BaseList
{
// Or use List<IBase>, if that's how you'll be using it more often.
private List<Base> list = new List<Base>();
public void Add<T>(T item) where T : Base, IBase
{
list.Add(item);
}
}
By using a generic method with both constraints, you can be sure that Add can only be called with an appropriate type argument.
You could have two methods to expose the data as IEnumerable<T> - one returning IEnumerable<IBase> (using Cast<T>) and one returning IEnumerable<Base>... that would let you use LINQ on either type, but not both at the same time of course.
I suspect you may find this awkward elsewhere, however - you may find yourself littering your code with generic methods which you wouldn't typically need. While there may well be a good reason for wanting both the class part and the interface part, it would be worth taking a step back and considering whether they're really both necessary. Is there something extra you could add to the interface so that you could do away with the class constraint, for example?
There is no good answer to your question because the design itself is not really fitting OOP as implemented in C#/.NET.
If you absolutely need a collection where each element statically provides two independent interfaces, either a wrapper collection or some wrapper class like Wrapper<TFirst, TSecond, T> : IBoth<TFirst, TSecond> would solve your problem.
Example:
public interface IBoth<TFirst, TSecond> {
TFirst AsFirst();
TSecond AsSecond();
}
public class Wrapper<T, TFirst, TSecond> : IBoth<TFirst, TSecond>
where T : TFirst, TSecond
{
private readonly T _value;
public Wrapper(T value) {
_value = value;
}
public TFirst AsFirst() {
return _value;
}
public TSecond AsSecond() {
return _value;
}
}
However the real question is why do you need that. Not to say that standard OOP model is perfect, but quite often a problem can be solved much easier if original design decisions are reviewed.
Another option is to completely ignore ServiceBase in most of the code and create a ServiceBaseAdapter for communication with the code that is not interface friendly. Such adapter can just call your interface methods when its method are called.
Try something like this:
List<object> collection = new List<object>();
foreach(var obj in collection.OfType<Base>().OfType<IBase>())
{
// Do what ever you want
}
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 am new to C#. Recently I have read an article.It suggests
"One of the practical uses of interface is, when an interface reference is created that can
work on different kinds of objects which implements that interface."
Base on that I tested (I am not sure my understanding is correct)
namespace InterfaceExample
{
public interface IRide
{
void Ride();
}
abstract class Animal
{
private string _classification;
public string Classification
{
set { _classification = value;}
get { return _classification;}
}
public Animal(){}
public Animal(string _classification)
{
this._classification = _classification;
}
}
class Elephant:Animal,IRide
{
public Elephant(){}
public Elephant(string _majorClass):base(_majorClass)
{
}
public void Ride()
{
Console.WriteLine("Elephant can ride 34KPM");
}
}
class Horse:Animal,IRide
{
public Horse(){}
public Horse(string _majorClass):base(_majorClass)
{
}
public void Ride()
{
Console.WriteLine("Horse can ride 110 KPH");
}
}
class Test
{
static void Main()
{
Elephant bully = new Elephant("Vertebrata");
Horse lina = new Horse("Vertebrata");
IRide[] riders = {bully,lina};
foreach(IRide rider in riders)
{
rider.Ride();
}
Console.ReadKey(true);
}
}
}
Questions :
Beyond such extend, what are the different way can we leverage the elegance of Interfaces ?
What is the Key point that I can say this can be only done by interface (apart from
multiple inheritances) ?
(I wish to gather the information from experienced hands).
Edit :
Edited to be concept centric,i guess.
The point is, you could also have a class Bike which implements IRide, without inheriting from Animal. You can think of an interface as being an abstract contract, specifying that objects of this class can do the things specified in the interface.
Because C# doesn't support multiple inheritance (which is a good thing IMHO) interfaces are the way you specify shared behavior or state across otherwise unrelated types.
interface IRideable
{
void Ride();
}
class Elephant : Animal, IRideable{}
class Unicycle: Machine, IRideable{}
In this manner, say you had a program that modeled a circus (where machines and animals had distinct behavior, but some machines and some animals could be ridden) you can create abstract functionality specific to what is means to ride something.
public static void RideThemAll(IEnumerable<IRideable> thingsToRide)
{
foreach(IRideable rideable in thingsToRide)
ridable.Ride();
}
As Lucero points out, you could implement other classes that implement IRide without inherting from Animal and be able to include all of those in your IRide[] array.
The problem is that your IRide interface is still too broad for your example. Obviously, it needs to include the Ride() method, but what does the Eat() method have to do with being able to ride a "thing"?
Interfaces should thought of as a loose contract that guarantees the existance of a member, but not an implementation. They should also not be general enough to span "concepts" (eating and riding are two different concepts).
You are asking the difference between abstract classes and interfaces. There is a really good article on that here.
Another great advantage is lower coupling between software components. Suppose you want to be able to feed any rideable animal. In this case you could write the following method:
public void Feed(IRide rideable)
{
//DO SOMETHING IMPORTANT HERE
//THEN DO SOMETHING SPECIFIC TO AN IRide object
rideable.Eat();
}
The major advantage here is that you can develop and test the Feed method without having any idea of the implementation of IRide passed in to this method. It could be an elephant, horse, or donkey. It doesn't matter. This also opens up your design for using Inversion of Control frameworks like Structure Map or mocking tools like Rhino Mock.
Interfaces can be used for "tagging" concepts or marking classes with specifically functionality such as serializable. This metadata (Introspection or Reflection) can be used with powerful inversion-of-control frameworks such as dependency injection.
This idea is used throughout the .NET framework (such as ISerializable) and third-party DI frameworks.
You already seem to grasp the general meaning of Interfaces.
Interfaces are just a contract saying "I support this!" without saying how the underlying system works.
Contrast this to a base or abstract class, which says "I share these common properties & methods, but have some new ones of my own!"
Of course, a class can implement as many interfaces as it wants, but can only inherit from one base class.