Understanding Interfaces in OOP - c#

I am trying to learn OOP concept at an advance level. I was reading through the topic interfaces and have a confusion. But first, let me show you what exactly caused this confusion.
I tested this Code Sample. but I am confused with the use of interfaces. After implementing that code, it seems to me that I can call the method DoFirst from class A by simply creating an instance of it. so why use an interface at first place?
Something like this:
A myA = new A();
myA.DoFirst();
and similiarly,
B myB = new B();
myB.DoFirst();
In both the classes, i have to implement a method called 'DoFirst', so what good does interface provided to me?
Can't I just write these methods in different classes myself?
my Second question, say I have an interface that has 5 methods. If a class implements it, and only wants to provide implementation of 3 methods instead of writing code of all 5 methods supplied by the interface. Isn't this useless? why have access methods that i don't want?
can somebody answer these with example (Highly appreciated) please?

The advantage was already pointed out in the link you provided...
Basically you can also write
void DoSomething(IMyInterface obj)
{
obj.DoFirst();
}
And then send any type of object which implements that interface as a parameter.
A myA = new A();
DoSomething(myA);
B myB = new B();
DoSomething(myB);
The method DoSomethig doesn't care about the object's type, as long as it exposes an interface called IMyInterface.

Some Real Life examples - also, another way/reason to use interfaces.
In my own code I have an Engine which processes code to produce reports in Excel. In this engine, i had to write the code two different ways, one using the Microsoft Excel Interop, the other using the Open Office Interop. Rather than duplicate my entire engine to work two different ways, or write a lot of if statements in all the actual interop functions, I implemented an interface. Then I declared two classes, each one implementing the interface, but one uses Excel and the other uses open office. Then, in my code, I simple reference the interface and its functions and use a single if statement at the very beginning of the function to tell the interface which class to implement.
public class ExcelEngineInterop : ISSinterface
{ ... }
public class OOEngineInterop : ISSinterface
{ ... }
//cant use two variables with the same name, so use 1 interface reference instead
ISSinterface ssInt;
if(ExcelFlag)
ssInt = new ExcelEngineInterop();
else
ssInt = new OOEngineInterop();
//two VERY different functions between Excel and OpenOffice.
ssInt.OpenApp();
ssInt.OpenFile(fileName);
//etc etc and so on
This is the other reason to use an interface. When you need one block of code to act two (or more) different ways depending on some external flag.
Another Example.
There is a top level form with lots of custom user controls under it. The user fires a form level event, like a button click, but depending on which user controls are active and what settings are on them at the time the click happens, the controls themselves need to do something different. Rather than writing what could be a rediculously large number of if statements to make sure each one acts correctly from the top level, just implement an interface on each control, then do something like this:
public ButtonClick(object sender, EventArgs e)
{
//note: I dont know which of my classes currentrightcontrol belongs to at the moment.
// it could be any one of 22 different controls. It must be cast to something
// in order to call the ButtonClick method (its actual type is generic "UserControl"
IMyRunControl ctrl = CurrentRightControl as IMyRunControl;
ctrl.FormButtonClicked();
}

C# is a statically typed language (at least unless you explicitly tell it not to be). This means that the compiler uses the type of the variable to know whether the referenced object has the members you are about to use.
The interface, therefore, provides a contract to the compiler (and to other programmers, too) that this class implements that interface. Because interfaces can be shared across classes that don't have a hierarchical relationship, this means that you can define a method that can take an object as an argument by defining that interface in the parameter type.

Related

C# generics with polymorphism

Hello denizens of stack overflow, I'm having an issue (perhaps with understanding?) regarding polymorphism and generics. I want to be able to define a "system" that contains a "component". I also want to be able to extend systems and components to be able to have greater functionality.
I currently have two base classes, Component, and I/A_ComponentSystem (For the sake of brevity, I'm not going to be showing any actual code, just definitions):
public abstract class Component { }
public interface IComponentSystem { }
public interface IComponentSystem<TComponent> : IComponentSystem
where TComponent : Component { }
// The following are what should should actually be inherited from
public abstract class AComponentSystem : IComponentSystem { }
public abstract class AComponentSystem<TComponent> : AComponentSystem
where TComponent : Component { }
Below is an example component/system created:
public abstract class ITag : Component { } // This is to allow generating the code in a different binary. Hard to explain in the question, I'll clarify if need be
public class Tag : ITag { }
public abstract class ITagSystem : AComponentSystem<ITag> { }
public class TagSystem : ITagSystem { }
Below are some excerpts of actually trying to use the code/morph between the different objects (please note that the code isn't meant to be used in this way, but I'm writing unit tests to ensure compatibility between layers)
// This is the main system that will be passed around
TagSystem tagSys = new TagSystem();
// This is OK
ITagSystem ITagSys = (ITagSystem)ITagSys;
// This is OK
AComponentSystem A_TagSys = (AComponentSystem)tagSys;
// This is OK
AComponentSystem<ITag> ATag_TagSys = (AComponentSystem<ITag>)tagSys;
// This is OK
IComponentSystem I_TagSys = (IComponentSystem)tagSys;
// This is OK
IComponentSystem<ITag> ITag_TagSys = (IComponentSystem<ITag>)tagSys;
// Even the following is OK (which is why I am confused)
IComponentSystem<Tag> new_ITag_TagSys = (IComponentSystem<Tag>)tagSys;
//***This is where it blows up*** (1)
AComponentSystem<Tag> new_ATag_TagSys = (AComponentSystem<Tag>)tagSys;
I have another interface/class, SystemManager, which is defined thusly:
public interface ISystemManager
{
TComponent AddNewComponentToEntity<TComponent, TComponentSystem>(Entity e) // Please don't ask about Entity, it shouldn't be required for this snippet and I already feel like I've posted a lot)
where TComponent : Component, new() // Required for some reason or I get an error
where TComponentSystem : IComponentSystem<TComponent>;
}
Now, the specific block of code that I have here will throw an error as well:
//*** blows up here as well ***(2)
ISystemManager sysMan = new SystemManager(); // defined elsewhere
sysMan.AddNewComponentToEntity<Tag, ITagSystem>(entity);
As far as the errors that I receive, error (1) is:
Cannot convert type 'TagSystem' to 'AComponentSystem<Tag>'
Error (2) is below:
The type 'ITagSystem' cannot be used as type parameter 'TComponentSystem' in the generic type or method 'ISystemManager.AddNewComponentToEntity<TComponent,TComponentSystem>(Entity)'. There is no implicit reference conversion from 'ITagSystem' to 'IComponentSystem<Tag>'.
Now, as far as my question goes, it is thusly:
Why can I not convert TagSystem to AComponentSystem<Tag>? This seems like a valid morph.
Why is ITagSystem not converting to IComponentSystem<Tag>? It appears that Tag should still conform to ITag, which is supported.
Is there any way I could change my hierarchy while preserving my need for that many layers of abstraction?
Thank you to anyone for reading this and assisting me.
Note: Yes, this is for an EntityFramework driven game engine. I'm building it mainly as an exercise for myself, and so I can quickly spin up 3d projects for myself. Yes, I've built a few game projects before, no I'm not interested in "finishing" a game, I'm just tinkering and having fun.
Without a simpler and yet more-complete code example, it's impossible to provide specific advice in your specific scenario. However, the basic problem is that the types are indeed not convertible, just as the compiler says.
Why can I not convert TagSystem to AComponentSystem<Tag>? This seems like a valid morph.
TagSystem doesn't inherit AComponentSystem<Tag>. It inherits AComponentSystem<ITag>. These two types are not actually the same. Just because Tag inherits/implements ITag, that does not mean that AComponentSystem<Tag> automatically inherits/implements AComponentSystem<ITag>. If it did, then that would mean that a method or property of AComponentSystem<Tag> that normally would return a value of type Tag, could wind up being used in a situation where a Tag value is expected, but some other implementation of ITag is actually returned. This is because you would be able to cast to AComponentSystem<Tag>, and then use that reference to return the non-Tag implementation of ITag, to some code that only wanted Tag.
This is bad for what I hope are obvious reasons, so the compiler doesn't allow you to do that.
Why is ITagSystem not converting to IComponentSystem<Tag>? It appears that Tag should still conform to ITag, which is supported.
Without a good Minimal, Complete, and Verifiable code example, it's difficult to answer this part of your question, as the types you've shown don't appear consistent with the code you've shown. ITagSystem is declared as inheriting AComponentSystem<ITag>, which in turn implements only IComponentSystem, not IComponentSystem<TComponent>.
So based on the code shown, there's no reason even naively to think that the conversion could work. But let's assume for a moment there's a typo in the type declarations you've shown. Then the answer is basically the same as above: implementing IComponentSystem<ITag> is not the same as implementing IComponentSystem<Tag>.
Is there any way I could change my hierarchy while preserving my need for that many layers of abstraction?
Possibly. It depends on what these types actually do. Since C# 4, we've been able to specify generic type parameters on interfaces with covariance and contravariance. With a type parameter thus restricted, and interface members to match, the interface then can support specific casting scenarios like you're trying to do.
But note that this only works when the interface members really are compatible with such conversions. The compiler still won't let you do anything unsafe.
There are a lot of questions on Stack Overflow already discussing this. Technically your question could even be considered a duplicate of those. I hope the above addresses your immediate concerns, and gives you enough information to do more research and see if generic interface variance will work in your situation. If you need more help, I recommend you post a new question and make sure to include a good MCVE that clearly illustrates your question in the simplest way possible.
TagSystem distantly inherits AComponentSystem<ITag>, but you are trying to convert it to AComponentSystem<Tag>. (Note the lack of an "I" in the generic type.) Those two generic types of AComponentSystem<> are completely different, and you cannot freely cast between the two.
Same as point 1, just because Tag is a child of ITag doesn't mean that IComponentSystem<Tag> is a child of IComponentSystem<ITag>.
The answer is almost certainly yes, though exactly how depends entirely on how you are going to use it. You might also want to ask yourself if you really need this many layers of abstraction.
To give a better example of my first point, take for example a common generic type: the List. If generics followed the same inheritance rules as normal classes, then List<Car> would be a subtype of List<Vehicle>. But the difference between the two is that the first list can only hold cars, while the second list can hold any vehicle. So if these lists were parent and child, you would be able to do the following:
List<Car> cars = new List<Car>();
List<Vehicle> vehicles = (List<Vehicle>)cars;
vehicles.Add(new Truck());
You see the problem? The general rules of inheritance just allowed us to add a non-Car object to out list of cars. Or they would, provided that is a legal cast, which it isn't. In reality, List<Car> and List<Vehicle> are not related in any way, but are actually completely separate classes with no direct relation whatsoever.

Hiding methods from other classes when inheriting from a class and Interface or Abstract class

To improve further implementation and to offer some guidelines and keep everything as universal as possible within the project I've created an Interface with a few methods which should be used. However only one method of this class should be visible to the user calling that class so I'd like them to be of the protected variety. E.g
public class ClassThree
{
public ClassThree()
{
var classOne = new ClassOne();
class1.MethodOne();
}
}
This despite ClassOne having 4 methods, 3 methods are used only within the one public class, hence private or protected. These 3 methods are required to make the 4th method work however (in an ideal world other developers would follow the same principle). So I don't want to see the following pop up on intellisense:
class1.MethodTwo();
class1.MethodThree();
class1.MethodFour();
I know one can implicitly call methods from an Interface e.g
IInterface.MethodTwo<Type,Type>(string name)
{
//Do stuff here
}
However I would like to prevent all the casting when calling said methods in ClassOne itself since this is just a thorn in my eye. I like my code clean and this isn't clean at all to me. I've thought of an abstract class however my class is inheriting from another class. With the interface I could just do
public ClassOne : ClassTwo, IInterface<Type1,Type2>
When I do that with an Abstract class however Visual Studio says an interface is expected. Any insights are most welcome and appreciated as I would like to up my code by making my life and that of fellow developers, who have to use my code, easier.
Thanks in advance!
Edit: The scenario is there can be several classes like ClassOne which essentially do the same however they use different types since the objects they have to return hold different values. However the buildup to these objects are more or less the same e.g:
Collect all API data
Retrieve the list to be exported to the API and call #3 or #4 depending on the type.
Export Type 1 to the API
Export Type 2 to the API
The idea is always the same but naturally different API's will require different variables. But to ensure all steps are followed as before I'd like to implement an Interface or something but step 1,2 and 3 should be private or protected and only step 2 should be available to the class that consumed it. However if I only put method 2 in the interface I can never be sure that others will implement 1,3 & 4. And that's kind of the goal here :P. This while ClassOne also inherits from another class and not just the interface.
Edit 2: I know Interfaces only provide public methods which is why I'm looking for alternatives hence this question. I know what is wrong with it I just don't really see how I can get it the way I would like it to be. Thanks for the replies so far!
Edit 3: Interface currently looks like this, I just adjusted variable names for sake of example.
public interface IExport<in T, in TU>
{
void GetRequiredApiData();
bool MethodOne(List<Type> list);
bool ExportOne(T one);
bool ExportTwo(TU two);
bool ValidateExport();
}
The other three methods should just be called inside your public method, or make your first method private/protected and call all 4 inside one public method.
The whole point of an interface is to hide exactly what is problematic for you--the other three methods that the caller doesn't need to know about.
I suspect you need to have those three methods called at separate, specific times, in a specific order. If that's the case then you have a code smell. Those methods are probably just void subroutines that have side effects and change global state. The code needs to be refactored to not be just a series of subroutines and objects need to be broken out differently.

Assigning "Actions" to objects

I'm developing a library in which I have two groups of classes:
A) a couple of classes with a bunch of functions, or "actions", already written in code
B) a few classes which must be "configured" when instantiated, in a way that the user using my library can instantiate objects from this second group of classes and "assign" actions from the first group
Right now I'm using delegates, like this:
Somwhere in the code I declare some delegates that are used by A and B:
public delegate void Action03(int value);
Then I have the "actions" implemented in the group A:
public Delegates.Action03 DoSomething03 = delegate(int value) { [code to execute when this action is specified on the constructor] };
And finally we use constructors like the following to instantiate objects from group B, where we pass as arguments the delegates/actions that we want:
public SomethingGroupB(Delegates.Action03 act03) { ... }
So of course, we can instantiate objects passing delegates as arguments:
SomethingGroupB somthg1 = new SomethingGroupB(GrpA01.DoSomething03);
But the whole point is that we can instantiate similar objects but assigning different actions:
SomethingGroupB somthg2 = new SomethingGroupB(GrpA07.DoSomething03);
SomethingGroupB somthg3 = new SomethingGroupB(GrpA01.DoSomething01);
SomethingGroupB somthg4 = new SomethingGroupB(GrpA02.DoWhatever);
So... as a summary, I want to have pre-coded (in my library) actions, and the user must choose the actions assigned to a new object when it is instantiated, and those actions don't change.
I guess I could also do it with events, but I don't need to add and remove "actions", they are fixed for the whole life of each object of type B.
So my question is: is there a better, nicer, cleaner solution than this one I've implemented with delegates?
Thank you very much!
So my question is: is there a better, nicer, cleaner solution than this one I've implemented with delegates?
The one improvement I would suggest would be to use the delegates defined in the framework, and not define your own. For example, your Action03 delegate is just a System.Action<int>. This would provide a bit more usability in terms of making the API more discoverable.
That being said, this is effectively using delegates to implement the Strategy pattern. Provided this provides the full functionality you need, it is potentially a good option here, and rather clean.
I think delegates is the only way to go.
Maybe you could also use a decorator pattern if it suits your need ? Its pretty clean, and because its a pattern, its standard, and "easy" to understand as its in some way normalized.
Cant think of any other way, appart maybe from having a heavier use of object composition (and then linking your objects together at runtime, which may be a bit more suple ?

Abstract Factory design pattern to create objects? Why can’t we just use the new operator?

why do we need a Abstract Factory design pattern to create objects? Why can’t we just use the new operator?
answer is, to avoid tight coupleing of the objects. But I didn't understand how ? can anyone explain with code (will be very useful).
what makes abstract factory design pattern useful and when.
Thanks in advance.
Harsha T
If you use the new operator, you have to specify which exact type you want.
Sometimes you want to be more generic, for example because you want to be able to change that instantiated type in all the codebase quickly.
An abstract factory design pattern is designed to create an object with a specific setup at initialization time. For example if you have a lot of similarly connected classes, rather than repeating the same 4+ lines [and using copying and pasting], the abstract factory would allow for you to keep the 4+ lines in a single location and reduce the amount of changes needed.
Reference For Abstract Factory
If you have :
class Foo implements DoSomething {...}
class Bar implements DoSomething {...}
obj = new Foo();
obj.doSomething();
Everywhere in your code, once you want to change all instances of Foo to use instances of Bar, are you really going to do search/replace ?
If you have :
obj = DoSomethingFactory.create();
obj.doSomething();
Inside the DoSomethingFactory, you can return any object you want that implements the DoSomething interface.
By using a Factory, you have the control over all the objects that are created by it.
If you decide to change the way the Factory creates objects, the changes take effect immediately in the code that uses the Factory.
Here's a simple example derived from a version independence layer I built for our product:
interface ICadSystemFactory
{
ICadSystem GetSystemInstance();
}
class 3dCadSystemVersion1 : ICadSystemFactory
{
ICadSystem GetSystemInstance()
{
return new 3dCadSystemWrapperVersion1(new 3dCadSystemVersion1());
}
}
class 3dCadSystemVersion2 : ICadSystemFactory
{
ICadSystem GetSystemInstance()
{
return new 3dCadSystemWrapperVersion2(new 3dCadSystemVersion2());
}
}
Where the 3dCadSystemWrapperVersionX objects implement the ICadSystem interface. I use a Registry object to decide what base factory I want to create based on certain version identifiers. This allows me to plug in new versions as needed without disturbing the existing infrastructure, which turns out to be useful in this case. It would, in fact, allow me to plug in whole new products if I needed to, which could generally be useful but in my case isn't worth the implementation effort.
There's a rather good C# example on Wikipedia. It keeps your application-level code from having to know which implementations it's getting. The factory takes care of it.
Using an abstract factory, you can create objects without knowledge of the actual type. Let's say you need a IDictionary. You could either create a new instance of a binary-tree-class that you happen to know, or you could tell the IDictionary-factory that you need a new instance. Then someone else could create a factory implementation that returns hash-tables, but everything on your side will still work the same way.
first of all you don't need to know the specific type of object your factory is instantiating,
then you can plug your factory classes around your project letting them instantiating objects for your components without having to use new in your code. The factory already do its dirty work
it conceptually separates the instantiation of object from their usage, keeping things decoupled

C# has abstract classes and interfaces, should it also have "mixins"?

Every so often, I run into a case where I want a collection of classes all to possess similar logic. For example, maybe I want both a Bird and an Airplane to be able to Fly(). If you're thinking "strategy pattern", I would agree, but even with strategy, it's sometimes impossible to avoid duplicating code.
For example, let's say the following apply (and this is very similar to a real situation I recently encountered):
Both Bird and Airplane need to hold an instance of an object that implements IFlyBehavior.
Both Bird and Airplane need to ask the IFlyBehavior instance to Fly() when OnReadyToFly() is called.
Both Bird and Airplane need to ask the IFlyBehavior instance to Land() when OnReadyToLand() is called.
OnReadyToFly() and OnReadyToLand() are private.
Bird inherits Animal and Airplane inherits PeopleMover.
Now, let's say we later add Moth, HotAirBalloon, and 16 other objects, and let's say they all follow the same pattern.
We're now going to need 20 copies of the following code:
private IFlyBehavior _flyBehavior;
private void OnReadyToFly()
{
_flyBehavior.Fly();
}
private void OnReadyToLand()
{
_flyBehavior.Land();
}
Two things I don't like about this:
It's not very DRY (the same nine lines of code are repeated over and over again). If we discovered a bug or added a BankRight() to IFlyBehavior, we would need to propogate the changes to all 20 classes.
There's not any way to enforce that all 20 classes implement this repetitive internal logic consistently. We can't use an interface because interfaces only permit public members. We can't use an abstract base class because the objects already inherit base classes, and C# doesn't allow multiple inheritance (and even if the classes didn't already inherit classes, we might later wish to add a new behavior that implements, say, ICrashable, so an abstract base class is not always going to be a viable solution).
What if...?
What if C# had a new construct, say pattern or template or [fill in your idea here], that worked like an interface, but allowed you to put private or protected access modifiers on the members? You would still need to provide an implementation for each class, but if your class implemented the PFlyable pattern, you would at least have a way to enforce that every class had the necessary boilerplate code to call Fly() and Land(). And, with a modern IDE like Visual Studio, you'd be able to automatically generate the code using the "Implement Pattern" command.
Personally, I think it would make more sense to just expand the meaning of interface to cover any contract, whether internal (private/protected) or external (public), but I suggested adding a whole new construct first because people seem to be very adamant about the meaning of the word "interface", and I didn't want semantics to become the focus of people's answers.
Questions:
Regardless of what you call it, I'd like to know whether the feature I'm suggesting here makes sense. Do we need some way to handle cases where we can't abstract away as much code as we'd like, due to the need for restrictive access modifiers or for reasons outside of the programmer's control?
Update
From AakashM's comment, I believe there is already a name for the feature I'm requesting: a Mixin. So, I guess my question can be shortened to: "Should C# allow Mixins?"
The problem you describe could be solved using the Visitor pattern (everything can be solved using the Visitor pattern, so beware! )
The visitor pattern lets you move the implementation logic towards a new class. That way you do not need a base class, and a visitor works extremely well over different inheritance trees.
To sum up:
New functionality does not need to be added to all different types
The call to the visitor can be pulled up to the root of each class hierarchy
For a reference, see the Visitor pattern
Cant we use extension methods for this
public static void OnReadyToFly(this IFlyBehavior flyBehavior)
{
_flyBehavior.Fly()
}
This mimics the functionality you wanted (or Mixins)
Visual Studio already offers this in 'poor mans form' with code snippets. Also, with the refactoring tools a la ReSharper (and maybe even the native refactoring support in Visual Studio), you get a long way in ensuring consistency.
[EDIT: I didn't think of Extension methods, this approach brings you even further (you only need to keep the _flyBehaviour as a private variable). This makes the rest of my answer probably obsolete...]
However; just for the sake of the discussion: how could this be improved? Here's my suggestion.
One could imagine something like the following to be supported by a future version of the C# compiler:
// keyword 'pattern' marks the code as eligible for inclusion in other classes
pattern WithFlyBehaviour
{
private IFlyBehavior_flyBehavior;
private void OnReadyToFly()
{
_flyBehavior.Fly();
}
[patternmethod]
private void OnReadyToLand()
{
_flyBehavior.Land();
}
}
Which you could use then something like:
// probably the attribute syntax can not be reused here, but you get the point
[UsePattern(FlyBehaviour)]
class FlyingAnimal
{
public void SetReadyToFly(bool ready)
{
_readyToFly = ready;
if (ready) OnReadyToFly(); // OnReadyToFly() callable, although not explicitly present in FlyingAnimal
}
}
Would this be an improvement? Probably. Is it really worth it? Maybe...
You just described aspect oriented programming.
One popular AOP implementation for C# seems to be PostSharp (Main site seems to be down/not working for me though, this is the direct "About" page).
To follow up on the comment: I'm not sure if PostSharp supports it, but I think you are talking about this part of AOP:
Inter-type declarations provide a way
to express crosscutting concerns
affecting the structure of modules.
Also known as open classes, this
enables programmers to declare in one
place members or parents of another
class, typically in order to combine
all the code related to a concern in
one aspect.
Could you get this sort of behavior by using the new ExpandoObject in .NET 4.0?
Scala traits were developed to address this kind of scenario. There's also some research to include traits in C#.
UPDATE: I created my own experiment to have roles in C#. Take a look.
I will use extension methods to implement the behaviour as the code shows.
Let Bird and Plane objects implement a property for IFlyBehavior object for an interface IFlyer
public interface IFlyer
{
public IFlyBehavior FlyBehavior
}
public Bird : IFlyer
{
public IFlyBehaviour FlyBehavior {get;set;}
}
public Airplane : IFlyer
{
public IFlyBehaviour FlyBehavior {get;set;}
}
Create an extension class for IFlyer
public IFlyerExtensions
{
public void OnReadyToFly(this IFlyer flyer)
{
flyer.FlyBehavior.Fly();
}
public void OnReadyToLand(this IFlyer flyer)
{
flyer.FlyBehavior.Land();
}
}

Categories