How to couple two classes in a generic way? - c#

I have classes for entities like Ship, Shampoo, Horse etc and each of them will have a manager class like ShipManager, ShampooManager, HorseManager etc. All the manager classes implement IManager and entities implement IEntity.
Now I have a static function written just to save the entities which would look like:
public static bool Save<S, T>(S entity, string msg) where S : IEntity
where T : IManager<S>, new()
{
string possibleError;
switch (new T().Save(entity, out possibleError))
{
//---------------------
}
return true;
}
The inelegance here is that I have to call the Save like Save<Radio, RadioManager> etc. What I would love to have is something like this:
public static bool Save<T>(T entity, string msg) where T : IEntity
{
string possibleError;
switch ((/*find manager here*/).Save(entity, out possibleError))
{
//---------------------
}
return true;
}
There are few ways to do this, but I would love to have something that involves generics and type inference. I am thinking it would be good to couple the entity classes with corresponding manager classes by design to achieve some type safety as well.
Here is what I could do, with the help of an extension method:
public static bool Save<T>(this IManager<T> mgr, T entity, string msg) where T : IEntity
{
string possibleError;
switch (mgr.Save(entity, out possibleError))
{
//---------------------
}
return true;
}
So that I can call:
FooManager fMgr = new FooManager();
fMgr.Save(foo, "success");
But here I always need to instantiate the IManager and then call the Save method on its instance. I would love to avoid that much repetitive code and give the duty to a static function. How can I design the classes to have a relationship between IManager and IEntity so that manager of entity is automatically inferred?
Edit: Please note that I dont have the luxury to move the Save method in manager class to entity class (which would have made life easier). Our entire design is based on one entity class and a corresponding manager class. So I am thinking of sticking to it.

Does the Client of FooManager care that it's a FooManager or that it's an IManager<Foo> ? If it just wants an IManager<Foo>, you probably want to look at the AbstractFactory pattern. Your factory would be responsible for instantiating/retrieving the correct IManager on demand. With the factory in place your save method would look something like this
public static bool Save<S>(S entity, string msg)
where S : IEntity
{
string possibleError;
switch (ManagerFactory.GetManagerFor<S>().Save(entity, out possibleError))
{
//---------------------
}
return true;
}
The simplest path for implementing your ManagerFactory is to use a service locator/dependency injector, and have it auto discover your IManager<T> implementations. Then your GetManagerFor method would just ask for an instance from the DI Container. For example, here's how to do it with AutoFac
var dataAssembly = Assembly.GetExecutingAssembly();
builder.RegisterAssemblyTypes(dataAssembly)
.Where(t => t.Name.EndsWith("Manager"))
.AsClosedTypesOf(typeof(IManager<>);
This will cause autofac to find all classes that end with "Manager" in their name in the current assembly and register as closed types of IManager<T>. So it would find FooManager and register it as an instance of IManager<Foo>
Now ManagerFactory just needs to call
return container.Resolve<IManager<Foo>>()
And you're golden. I'm not going to write your application for you but this should give you enough to get you going. Read the docs on AutoFac, it's really powerful because it can also build up objects for you using dependency injection as well and it's a great tool to have in your belt.

Here is how I solved it.
I created a function Manager in the IEntity like this:
IManager<T> Manager<T>() where T : IEntity;
Now whenever I implement IEntity in any of the entity classes, I am forced to implement their respective Manager as well. For eg.
public class Foo : IEntity
{
public IManager<T> Manager<T>() where T : IEntity
{
return (IManager<T>)new FooManager();
}
}
Now I can call:
public static bool Save<T>(T entity, string msg) where T : IEntity, new()
{
string possibleError;
switch (entity.Manager<T>().Save(entity, out possibleError))
{
//--------------------------------------
}
return true;
}
Not the best of designs, but this does the job..

Related

Making covariant interface backward compatible

We have an interface to deal with DAL with pretty simple definition:
interface IRepository<T> : IQueriable<T> // so we can read data from database
{
Save(T document); // dozen of methods here
}
Mostly we use two implementations: real version and in memory version for unit testing. Here is declarations of one of class:
public RealRepository : IRepository<AccountEntity> { ... }
// typical IOC usage
services.AddSingleton<IRepository<AccountEntity>, RealRepository<AccountEntity>>();
Now we are working to spin off for main codebase to custom version of project and we need custom fields in data and occassional custom behavior in repository. Most of classes are fine with base implementation but others would require specific implementation. So my goal is to get to following services in:
var repository = new RealRepository<CustomAccountEntity>();
services.AddSingleton(IRepository<AccountEntity>, repository);
// for new classes
services.AddSingleton(IRepository<CustomAccountEntity>, repository);
I tried to add out T to IRepository but I am using T in input parameters and this gave compile time "Invalid variance" error.
I can see a solution by adding second type parameter to interface so it looks like:
IRepository<TBase, out TChild> : IQueriable<TChild> {
Save (T document);
}
Finally, Question: How can make change 100% backward compatible?
What I tried:
Add IRepository<T>: IRepository<T,T> -> complies, but RealRepository is not implementing IRepository anymore.
Add 2 interfaces in implementation: public class RealRepository<TBase, TChild>: IRepository<TBase, TChild>, IRepository<TChild> but this gives compliation error 'cannot implement both ... and ... because they may unify for some type parameter substitutions'
Save(T document) has T in a contravariant position. That means in T, not out T.
Let's recap what contravariance means. Suppose you had this code:
using System;
public class Entity {}
public class AccountEntity : Entity {}
public class CustomAccountEntity : AccountEntity {}
public interface IQueryable<in T>
where T : Entity
{}
public interface IRepository<in T>
where T : Entity
{
void Save(T record);
}
public class EntityRepository<T> : IRepository<T>
where T : Entity
{
public void Save(T record) {}
}
public class Program
{
public static void Main()
{
// This is ***VALID***:
IRepository<CustomAccountEntity> repo = new EntityRepository<AccountEntity>();
Console.WriteLine(repo == null ? "cast is invalid" : "cast is valid");
}
}
https://dotnetfiddle.net/cnEdcm
So whenever you need a IRepository<CustomAccountEntity>, you can use a concrete EntityRepository<AccountEntity> instance. Seems counter-intuitive, but it's actually totally right: If the concrete method is Save(AccountEntity), it can obviously handle CustomAccountEntity instances too; OTOH if the concrete method were Save(CustomAccountEntity), it would NOT be able to handle simple AccountEntity instances.
Having said that, then I think you should
Use contravariance instead;
Declare all dependencies using the most specialised type, e.g. IRepository<CustomWhateverEntity>;
In the IoC registration code, for each particular entity, setup either Repository<CustomeWhateverEntity>, if you need the extra behaviour, or just Repository<WhateverEntity> otherwise.

Injecting parents into composite constructors with Unity C#

I am trying to get IoC working with Unity in C# with the idea of a passing a wrapper/composite class into the children.
The top level class that composes multiple classes provides some common functionality that the composed classes require access to.
To illustrate:
// The top composite class
public class Context : IContext {
public ISomething SomethingProcessor { get; }
public IAnother AnotherProcessor { get; }
public Context(ISomething something, IAnother another) {
this.SomethingProcessor = something;
this.AnotherProcessor = processor;
}
// A function that individual classes need access to, which itself calls one of the children.
public string GetCommonData() {
return this.AnotherProcessor.GetMyData();
}
}
public class Something : ISomething {
private _wrapper;
public Something(IContext context) {
this._wrapper = context;
}
// This class has no knowledge of IAnother, and requests data from the master/top class, which knows where to look for whatever.
public void Do() {
Console.WriteLine(_wrapper.GetCommonData());
}
}
public class Another : IAnother {
public string GetMyData() {
return "Foo";
}
}
If you didn't use IoC, it's easy, as the constructor for the Context class becomes:
public Context() {
this.SomethingProcessor = new Processor(this);
this.AnotherProcessor = new Another();
}
But when you're using IoC, the idea of "this" doesn't exist yet because it is yet to be constructed by the injector. Instead what you have a is a circular dependency.
container.RegisterType<ISomething, Something>();
container.RegisterType<IAnother, Another>();
container.RegisterType<IContext, Context>();
var cxt = container.Resolve<IContext>(); // StackOverflowException
The above example has been greatly simplified to illustrate the concept. I'm struggling to find the "best practice" way of dealing with this kind of structure to enable IOC.
Factory pattern is a way construct an object based on other dependencies or logical choices.
Factory Method: "Define an interface for creating an object, but let
the classes which implement the interface decide which class to
instantiate. The Factory method lets a class defer instantiation to
subclasses" (c) GoF.
Lots of construction.. hence the name Factory Pattern
A crude code sample that could be used with DI
public class ContextFactory : IContextFactory {
_anotherProcessor = anotherProcessor;
public ContextFactory(IAnotherProcessor anotherProcessor) {
//you can leverage DI here to get dependancies
}
public IContext Create(){
Context factoryCreatedContext = new Context();
factoryCreatedContext.SomethingProcessor = new SomethingProcessor(factoryCreatedContext )
factoryCreatedContext.AnotherProcessor = _anotherProcessor;
//You can even decide here to use other implementation based on some dependencies. Useful for things like feature flags.. etc.
return context;
}
}
You can get away with this, maybe? - but there is still the cyclic reference issue here and I would never commit this kind of code.
The problem here you need to concentrate on Inversion Of Control of that GetCommonData
Your SomethingProcessor should not rely on methods in another class. This is where In Inheritance could be used but Inheritance can become very complicated very quickly.
The best way forward is to Identify the ONE thing that is needed by both or many other places and break that out into a new Dependency. That is how you Invert Control.
TIP:
Don't overdo Interfaces- Use Interfaces where you think you will be working with Polymorphism, such as a collection of different objects that must promise you they have implemented a specific method/property. Otherwise you are over using Interfaces and increasing complexity. DI doesn't have to use Interfaces it can be a concrete implementation. Interfaces on Repositories are a good use since you can switch Databases out easily but Interfaces a factory like this is not really needed.
I don't know the name of this pattern, or even if it is a bad or good practice, but you can solve your problem of "double-binding" by creating a method to bind the "IContext", instead of doing it in the constructor.
For instance,
1) ISomething has a void BindContext(IContext context) method
2) You implement it as such :
class Something : ISomething
{
IContext _wrapper;
// ... nothing in constructor
public void BindContext(IContext context)
{
_wrapper = context;
}
}
3) Remove the IContext dependency injection in Something constructor.
And you call it from the context constructor :
public Context(ISomething something, IAnother another) {
this.SomethingProcessor = something;
this.SomethingProcessor.BindContext(this);
// same for IAnother
}
And you do the same for IAnother. You could even extract some common interface "IBindContext" to make things a beat more "DRY" (Don't Repeat yourself) and make IAnother and ISomething inherit from it.
Not tested, and again : not sure it's the best way to do such dependency design. I'll be glad if there is another answer which gives a state-of-the-art insight about this.

Unit Of Work Pattern - Getting repositories with a factory

I am following a tutorial to do with the Repository Pattern in a combination with the Unit Of Work pattern.
I essentially have:
interface IRepository<T> where T : class
{
//...
}
class Repository<T> where T : class
{
//Implemented methods
}
interface IFooRepository
{
IQueryable<Foo> GetFoos();
}
class FooRepository : Repository<Foo>, IFooRepository
{
IQueryable<Foo> GetFoos() {}
}
The above represents my repositories, in a basic sense. I then have a Uow class.
public class MyUow
{
public void Commit() { }
public IRepository<Bar> Bars { get { return GetStandardRepo<Bar>(); } }
public IFooRepository Foos { get { return GetRepo<IFooRepository>(); } }
private IRepository<T> GetStandardRepo()
{
return RepositoryProvider.GetRepoistoryForEntityType<T>();
}
private T GetRepo<T>()
{
return RepositoryProvider.GetRepository<T>();
}
}
My problem is coming where the tutorial I am following only ever instansiates a Dictionairy<Type, object> in the RepositoryProvider class and doesn't seem to fill it, so the method used in GetRepo<T> doesn't work.
public virtual T GetRepository<T>(Func<DbContext, object> factory = null) where T : class
{
//Look for T in the dictionairy by typeof(T)
object repoObj;
Repositories.TryGetValue(typeof(T), out repoObj);
if (repoObj != null)
return (T)repoObj;
//Not found or a null value, make a new instance of the repository.
return MakeRepository<T>(factory, Context);
}
private T MakeRepository<T>(Func<DbContext, object> factory, DbContext dbContext) where T : class
{
var f = factory ?? _repositoryFactories.GetRepositoryFactory<T>();
if (f == null)
//Exception here because this is null
throw new NotImplementedException("No factory for repository type");
var repo = (T)f(dbContext);
Repositories[typeof(T)] = repo;
return repo;
}
My question is essentially what is the correct way to implement this pattern and where I am going wrong? Should I instansiate the Dictionairy<Type, Func<DbContext, object> with a the list of known repositories? This seems dirty. I am driving myself insane trying to solve this!
Thanks in advance.
What I see from beginning is that your Repository<T> doesn't implement IRepository<T>, so it should be like this:
class Repository<T> : IRepository<T> where T : class
{
//Implemented methods
}
Then your completely secret tutorial should describe how _repositoryFactories.GetRepositoryFactory<T>() can discover your IRepository<T> implementor FooRepository - maybe it willbe autodiscovery, maybe you need to register something somewhere.
Next, again I know nothing about your specific tutorial and factories etc, but I suppose you may need to use GetRepo<Foo> instead of GetRepo<IFooRepository>, because right now this IFooRepository looks meaningless... or maybe again you miss something in this IFooRepository declaration, and it should be like interface IFooRepository : IRepository<Foo> - and again, it greatly depends on particular discovery implementation for factories you are using.
In case you have not found the answer yet, I followed through the tutorial and was able to run it (the tutorial sample). If you're sure that you have implemented it right, take note of this,
The Repository Dictionary is by default, null and will only have value of the not standard repos (e.g. IFooRepository) when it is first requested. Therefore, if you're checking the value in debug of the Repository Dictionary and an IFooRepository is not yet requested it is for sure that you will not see it there. Have a code to access the IFooRepository first then it will make a repository for that in the MakeRepository method of the provider class.
Hope that helps
There is a helper class called RepositoryFactories.cs
You need to add an entry for your custom Repository to the dictionary
{typeof(IFooRepository ), dbContext => new FooRepository (dbContext)}

Letting only the abstract class know about its inheritors

I am making a payment system for my site. Users can select one of several payment providers to pay, but all should behave in the same way. I thought to represent this behavior like this:
public abstract class PaymentProvider {
private static var methods = Dictionary<String,PaymentProvider>
{
{"paypal",new PaymentProviderPaypal()},
{"worldpay",new PaymentProviderWorldpay()}
}
public static Dictionary<String,PaymentProvider> AllPaymentProviders
{
get {return methods;}
}
public abstract pay();
}
public class PaymentProviderPaypal : PaymentProvider {
public override pay() {
}
}
public class PaymentProviderWorldpay : PaymentProvider {
public override pay() {
}
}
You are supposed to use this by writing PaymentProvider.AllPaymentProviders["key"].pay(). The idea is that the functions using this class don't need to know about how the underlying payment provider is implemented, they just need to know the key.
However, at the moment, if you have access to the PaymentProvider class, you also have access to the inheriting classes. Its possible to instantiate a new copy of the inheriting classes, and make use of them in an unexpected way. I want to encapsulate the inheriting classes so that only the abstract PaymentProvider knows about them.
How should I do this? Different protection levels like protected don't work here - In Java, protected means that only other classes in the namespace can use that class, but in C# it means something else.
Do I have the right idea here? Or should I use a different method?
A couple of options spring to mind:
Put this in a separate assembly from the client code, and make the implementations abstract
Put the implementations inside the PaymentProvider class as private nested classes. You can still separate the source code by making PaymentProvider a partial class - use one source file per implementation
The first option is likely to be the cleanest if you don't mind separating the clients from the implementation in terms of assemblies.
Note that both of these are still valid options after the change proposed by Jamiec's answer - the "visibility" part is somewhat orthogonal to the inheritance part.
(As an aside, I hope the method is really called Pay() rather than pay() :)
Your inheritance heirachy is a bit wonky, I would be tempted to do it a similar but crucially different way.
public interface IPaymentProvider
{
void Pay()
}
// Implementations of IPaymentProvider for PaypalPaymentProvider & WorldpayPaymentProvider
public static class PaymentHelper
{
private static var providers = Dictionary<String,IPaymentProvider>
{
{"paypal",new PaymentProviderPaypal()},
{"worldpay",new PaymentProviderWorldpay()}
}
public static void Pay(string provider)
{
if(!providers.Containskey(provider))
throw new InvalidOperationException("Invalid provider: " + provider);
providers[provider].Pay();
}
}
Then the usage would be something like PaymentHelper.Pay("paypal").
Obviously if there is more data to provide to the Pay method this can be added to both the interface, and the helper. for example:
public interface IPaymentProvider
{
void Pay(double amount);
}
public static void Pay(string provider, double amount)
{
if(!providers.Containskey(provider))
throw new InvalidOperationException("Invalid provider: " + provider);
providers[provider].Pay(amount);
}

Using Interface variables

I'm still trying to get a better understanding of Interfaces. I know about what they are and how to implement them in classes.
What I don't understand is when you create a variable that is of one of your Interface types:
IMyInterface somevariable;
Why would you do this? I don't understand how IMyInterface can be used like a class...for example to call methods, so:
somevariable.CallSomeMethod();
Why would you use an IMyInterface variable to do this?
You are not creating an instance of the interface - you are creating an instance of something that implements the interface.
The point of the interface is that it guarantees that what ever implements it will provide the methods declared within it.
So now, using your example, you could have:
MyNiftyClass : IMyInterface
{
public void CallSomeMethod()
{
//Do something nifty
}
}
MyOddClass : IMyInterface
{
public void CallSomeMethod()
{
//Do something odd
}
}
And now you have:
IMyInterface nifty = new MyNiftyClass()
IMyInterface odd = new MyOddClass()
Calling the CallSomeMethod method will now do either something nifty or something odd, and this becomes particulary useful when you are passing in using IMyInterface as the type.
public void ThisMethodShowsHowItWorks(IMyInterface someObject)
{
someObject.CallSomeMethod();
}
Now, depending on whether you call the above method with a nifty or an odd class, you get different behaviour.
public void AnotherClass()
{
IMyInterface nifty = new MyNiftyClass()
IMyInterface odd = new MyOddClass()
// Pass in the nifty class to do something nifty
this.ThisMethodShowsHowItWorks(nifty);
// Pass in the odd class to do something odd
this.ThisMethodShowsHowItWorks(odd);
}
EDIT
This addresses what I think your intended question is - Why would you declare a variable to be of an interface type?
That is, why use:
IMyInterface foo = new MyConcreteClass();
in preference to:
MyConcreteClass foo = new MyConcreteClass();
Hopefully it is clear why you would use the interface when declaring a method signature, but that leaves the question about locally scoped variables:
public void AMethod()
{
// Why use this?
IMyInterface foo = new MyConcreteClass();
// Why not use this?
MyConcreteClass bar = new MyConcreteClass();
}
Usually there is no technical reason why the interface is preferred. I usually use the interface because:
I typically inject dependencies so the polymorphism is needed
Using the interface clearly states my intent to only use members of the interface
The one place where you would technically need the interface is where you are utilising the polymorphism, such as creating your variable using a factory or (as I say above) using dependency injection.
Borrowing an example from itowlson, using concrete declaration you could not do this:
public void AMethod(string input)
{
IMyInterface foo;
if (input == "nifty")
{
foo = new MyNiftyClass();
}
else
{
foo = new MyOddClass();
}
foo.CallSomeMethod();
}
Because this:
public void ReadItemsList(List<string> items);
public void ReadItemsArray(string[] items);
can become this:
public void ReadItems(IEnumerable<string> items);
Edit
Think of it like this:
You have to be able to do this.
rather than:
You have to be this.
Essentially this is a contract between the method and it's callers.
Using interface variables is the ONLY way to allow handler methods to be written which can accept data from objects that have different base classes.
This is about as clear as anyone is going to get.
An interface is used so you do not need to worry about what class implements the interface. An example of this being useful is when you have a factory method that returns a concrete implementation that may be different depending on the environment you are running in. It also allows an API designer to define the API while allowing 3rd parties to implement the API in any way they see fit. Sun does this with it's cryptographic API's for Java.
public interface Foo {
}
public class FooFactory {
public static Foo getInstance() {
if(os == 'Windows') return new WinFoo();
else if(os == 'OS X') return new MacFoo();
else return new GenricFoo();
}
}
Your code that uses the factory only needs to know about Foo, not any of the specific implementations.
I was in same position and took me few days to figure out why do we have to use interface variable.
IDepartments rep = new DepartmentsImpl();
why not
DepartmentsImpl rep = new DepartmentsImpl();
Imagine If a class implements two interfaces that contain a member with the same signature, then implementing that member on the class will cause both interfaces to use that member as their implementation.
class Test
{
static void Main()
{
SampleClass sc = new SampleClass();
IControl ctrl = (IControl)sc;
ISurface srfc = (ISurface)sc;
// The following lines all call the same method.
sc.Paint();
ctrl.Paint();
srfc.Paint();
}
}
interface IControl
{
void Paint();
}
interface ISurface
{
void Paint();
}
class SampleClass : IControl, ISurface
{
// Both ISurface.Paint and IControl.Paint call this method.
public void Paint()
{
Console.WriteLine("Paint method in SampleClass");
}
}
// Output:
// Paint method in SampleClass
// Paint method in SampleClass
// Paint method in SampleClass
If the two interface members do not perform the same function, however, this can lead to an incorrect implementation of one or both of the interfaces.
public class SampleClass : IControl, ISurface
{
void IControl.Paint()
{
System.Console.WriteLine("IControl.Paint");
}
void ISurface.Paint()
{
System.Console.WriteLine("ISurface.Paint");
}
}
The class member IControl.Paint is only available through the IControl interface, and ISurface.Paint is only available through ISurface. Both method implementations are separate, and neither is available directly on the class. For example:
IControl c = new SampleClass();
ISurface s = new SampleClass();
s.Paint();
Please do correct me if i am wrong as i am still learning this Interface concept.
Lets say you have class Boat, Car, Truck, Plane.
These all share a common method TakeMeThere(string destination)
You would have an interface:
public interface ITransportation
{
public void TakeMeThere(string destination);
}
then your class:
public class Boat : ITransportation
{
public void TakeMeThere(string destination) // From ITransportation
{
Console.WriteLine("Going to " + destination);
}
}
What you're saying here, is that my class Boat will do everything ITransportation has told me too.
And then when you want to make software for a transport company. You could have a method
Void ProvideServiceForClient(ITransportation transportationMethod, string whereTheyWantToGo)
{
transportationMethod.TakeMeThere(whereTheyWantToGo); // Cause ITransportation has this method
}
So it doesn't matter which type of transportation they want, because we know it can TakeMeThere
This is not specific to C#,so i recommend to move to some othere flag.
for your question,
the main reason why we opt for interface is to provide a protocol between two components(can be a dll,jar or any othere component).
Please refer below
public class TestClass
{
static void Main()
{
IMyInterface ob1, obj2;
ob1 = getIMyInterfaceObj();
obj2 = getIMyInterfaceObj();
Console.WriteLine(ob1.CallSomeMethod());
Console.WriteLine(obj2.CallSomeMethod());
Console.ReadLine();
}
private static bool isfirstTime = true;
private static IMyInterface getIMyInterfaceObj()
{
if (isfirstTime)
{
isfirstTime = false;
return new ImplementingClass1();
}
else
{
return new ImplementingClass2();
}
}
}
public class ImplementingClass1 : IMyInterface
{
public ImplementingClass1()
{
}
#region IMyInterface Members
public bool CallSomeMethod()
{
return true;
}
#endregion
}
public class ImplementingClass2 : IMyInterface
{
public ImplementingClass2()
{
}
#region IMyInterface Members
public bool CallSomeMethod()
{
return false;
}
#endregion
}
public interface IMyInterface
{
bool CallSomeMethod();
}
Here the main method does not know about the classes still it is able to get different behaviour using the interface.
The purpose of the Interface is to define a contract between several objects, independent of specific implementation.
So you would usually use it when you have an Intrace ISomething, and a specific implementation
class Something : ISomething
So the Interface varialbe would come to use when you instantiate a contract:
ISomething myObj = new Something();
myObj.SomeFunc();
You should also read interface C#
Update:
I will explaing the logic of using an Interface for the variable and not the class itself by a (real life) example:
I have a generic repositor interace:
Interface IRepository {
void Create();
void Update();
}
And i have 2 seperate implementations:
class RepositoryFile : interface IRepository {}
class RepositoryDB : interface IRepository {}
Each class has an entirely different internal implementation.
Now i have another object, a Logger, that uses an already instansiated repository to do his writing. This object, doesn't care how the Repository is implemented, so he just implements:
void WriteLog(string Log, IRepository oRep);
BTW, this can also be implemented by using standard classes inheritance. But the difference between using interfaces and classes inheritance is another discussion.
For a slightly more details discussion on the difference between abstract classes and interfaces see here.
Say, for example, you have two classes: Book and Newspaper. You can read each of these, but it wouldn't really make sense for these two to inherit from a common superclass. So they will both implement the IReadable interface:
public interface IReadable
{
public void Read();
}
Now say you're writing an application that will read books and newspapers for the user. The user can select a book or newspaper from a list, and that item will be read to the user.
The method in your application that reads to the user will take this Book or Newspaper as a parameter. This might look like this in code:
public static void ReadItem(IReadable item)
{
item.Read();
}
Since the parameter is an IReadable, we know that the object has the method Read(), thus we call it to read it to the user. It doesn't matter whether this is a Book, Newspaper, or anything else that implements IReadable. The individual classes implement exactly how each item will be read by implementing the Read() method, since it will most likely be different for the different classes.
Book's Read() might look like this:
public void Read()
{
this.Open();
this.TurnToPage(1);
while(!this.AtLastPage)
{
ReadText(this.CurrentPage.Text);
this.TurnPage();
}
this.Close();
}
Newspaper's Read() would likely be a little different:
public void Read()
{
while(!this.OnBackPage)
{
foreach(Article article in this.CurrentPage.Articles)
{
ReadText(article.Text);
}
}
}
The point is that the object contained by a variable that is an interface type is guaranteed to have a specific set of methods on it, even if the possible classes of the object are not related in any other way. This allows you to write code that will apply to a variety of classes that have common operations that can be performed on them.
No, it is not possible. Designers did not provide a way. Of course, it is of common sense also. Because interface contains only abstract methods and as abstract methods do not have a body (of implementation code), we cannot create an object..
Suppose even if it is permitted, what is the use. Calling the abstract method with object does not yield any purpose as no output. No functionality to abstract methods.
Then, what is the use of interfaces in Java design and coding. They can be used as prototypes from which you can develop new classes easily. They work like templates for other classes that implement interface just like a blue print to construct a building.
I believe everyone is answering the polymorphic reason for using an interface and David Hall touches on partially why you would reference it as an interface instead of the actual object name. Of course, being limited to the interface members etc is helpful but the another answer is dependency injection / instantiation.
When you engineer your application it is typically cleaner, easier to manage, and more flexible if you do so utilizing dependency injection. It feels backwards at first if you've never done it but when you start backtracking you'll wish you had.
Dependency injection normally works by allowing a class to instantiate and control the dependencies and you just rely on the interface of the object you need.
Example:
Layer the application first. Tier 1 logic, tier 2 interface, tier 3 dependency injection. (Everyone has their own way, this is just for show).
In the logic layer you reference the interfaces and dependency layer and then finally you create logic based on only the interfaces of foreign objects.
Here we go:
public IEmployee GetEmployee(string id)
{
IEmployee emp = di.GetInstance<List<IEmployee>>().Where(e => e.Id == id).FirstOrDefault();
emp?.LastAccessTimeStamp = DateTime.Now;
return emp;
}
Notice above how we use di.GetInstance to get an object from our dependency. Our code in that tier will never know or care about the Employee object. In fact if it changes in other code it will never affect us here. If the interface of IEmployee changes then we may need to make code changes.
The point is, IEmployee emp = never really knows what the actual object is but does know the interface and how to work with it. With that in mind, this is when you want to use an interface as opposed to an object becase we never know or have access to the object.
This is summarized.. Hopefully it helps.
This is a fundamental concept in object-oriented programming -- polymorphism. (wikipedia)
The short answer is that by using the interface in Class A, you can give Class A any implementation of IMyInterface.
This is also a form of loose coupling (wikipedia) -- where you have many classes, but they do not rely explicitly on one another -- only on an abstract notion of the set of properties and methods that they provide (the interface).

Categories

Resources