Can interface implementations be restricted to an assembly? - c#

I can restrict C# class inheritance to the assembly through internal or private protected constructors. But is something similar possible with interfaces?
Why I want this?
I try to create a framework where specific interfaces exist. For simplicity I call them IInput, IOutput and IInAndOut. The latter inherits the other two.
Those can be used in several places in the framework and there are many implementations provided by the framework as well. Now I want to prevent the user from providing his own implementation. He should only be able to use existing implementations or derive from more specialized classes which already implement the interface.
I could do this with abstract classes instead which have private protected ctors but this won't allow to inherit two other abstract classes.
So I need something like a sealed or use-only interface which can only be implemented in my own assembly.
Is there something like this in C#?

For the users of the framework I would suggest to offer classes where the specific IO methods are implemented. To prevent the users from overriding these methods, they can be marked as sealed, but the classes may be used as base classes for new derived classes.
For the developers of the framework you can use interfaces. In this case I would suggest to declare the interfaces as internal since you don't want the framework's users to implement the interfaces and, consequently, they don't need to see the interfaces. Currently (since C# 8.0), interfaces can contain implementations of some or all methods if this is convenient in the project.
Another option for the framework developers is to offer abstract classes, where the specific IO methods are marked as abstract. Also in this case a class can contain an implementation of a method, which would not be marked as abstract, but rather as virtual. Abstract classes have an advantage over interfaces that they enforce a more rigid structure of project components.

Yes you can make a public interface which can only be implemented internally but it requires a little work around as there is no keyword for this.
//Your framework class implementing interface that is publicly accessible but cannot be implemented outside of your framework assembly.
public class FrameworkClass : IFrameworkOnlyInterface
{
NotImplementable IFrameworkOnlyInterface.CannotBeImplemented()
{
return null;
}
}
//Your interface that will be visible and accessible for user of your framework but cannot be implemented in outside assemblies.
public interface IFrameworkOnlyInterface
{
//A throw-away internal method returning internal type to dissalow implementation from outside of this assembly.
internal NotImplementable CannotBeImplemented();
}
//Internal class used as a throw-away type to dissalow implementation of public interface outside of your assembly.
internal class NotImplementable
{
}
Users of your framework will be able to derive from your FrameworkClass and use it as normal, they will also be able to cast it to IFrameworkOnlyInterface and use its methods apart from CannotBeImplemented() method or any other method you mark as internal.
If you do not want users to access IFrameworkOnlyInterface at all then all you have to do is mark the IFrameworkOnlyInterface as internal.

Related

Difference between interface with default method and abstract class in C#? [duplicate]

I know that an abstract class is a special kind of class that cannot be instantiated. An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but, it cannot be instantiated. The advantage is that it can enforce certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.
Also I know that An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn’t support multiple inheritance, interfaces are used to implement multiple inheritance.
When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.
When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface.
BUT
BUT
BUT
I noticed that we will have Default Interface Methods in C# 8.0
Maybe I'm asking it because I have only 1-2 years of experience in programming, but what would be main difference between abstract class and interface now?
I know that we can't make state in interface, will it be only one difference between them?
Conceptual
First of all, there is a conceptual difference between a class and an interface.
A class should describe an "is a" relationship. E.g. a Ferrari is a Car
An interface should describe a contract of a type. E.g. A Car has a steering wheel.
Currently abstract classes are sometimes used for code reuse, even when there is no "is a" relationship. This pollutes the OO design. E.g. FerrariClass inherits from CarWithSteeringWheel
Benefits
So from above, you could reuse code without introducing a (conceptually wrong) abstract class.
You could inherit from multiple interfaces, while an abstract class is only single inheritance
There is co- and contravariance on interfaces and not on classes in C#
It's easier to implement an interface because some methods have default implementations. This could save a lot of work for an implementer of the interface, but the user won't see the difference :)
But most important for me (as I'm a library maintainer), you could add new methods to an interface without making a breaking change! Before C# 8, if an interface was publicly published, it should be fixed. Because changing the interface could break a lot.
The logger interface
This example shows some of the benefits.
You could describe a (oversimplified) logger interface as follows:
interface ILogger
{
void LogWarning(string message);
void LogError(string message);
void Log(LogLevel level, string message);
}
Then a user of that interface could log easily as warning and error using LogWarning and LogError. But the downside is that an implementer must implement all the methods.
An better interface with defaults would be:
interface ILogger
{
void LogWarning(string message) => Log(LogLevel.Warning, message);
void LogError(string message) => Log(LogLevel.Error, message);
void Log(LogLevel level, string message);
}
Now a user could still use all the methods, but the implementer only needs to implement Log. Also, he could implement LogWarning and LogError.
Also, in the future you might like to add the logLevel "Catastrophic". Before C#8 you could not add the method LogCatastrophic to ILogger without breaking all current implementations.
There is not a lot of difference between the two apart from the obvious fact that abstract classes can have state and interfaces cannot. Default methods or also known as virtual extension methods have actually been available in Java for a while. The main drive for default methods is interface evolution which means being able to add methods to an interface in future versions without breaking source or binary compatibility with existing implementations of that interface.
another couple of good points mentioned by this post:
The feature enables C# to interoperate with APIs targeting Android
(Java) and iOs (Swift), which support similar features.
As it turns out, adding default interface implementations provides
the elements of the "traits" language feature
(https://en.wikipedia.org/wiki/Trait_(computer_programming)). Traits
have proven to be a powerful programming technique
(http://scg.unibe.ch/archive/papers/Scha03aTraits.pdf).
Another thing which still makes the interface unique is covariance / contravariance.
To be honest, never found myself in situation where a default impl. in interface was the solution. I am a bit sceptical about it.
Both abstract classes and the new default interface methods have their appropriate uses.
A. Reasons
Default interface methods have not been introduced to substitute abstract classes.
What's new in C# 8.0 states:
This language feature enables API authors to add methods to an interface in later versions without breaking source or binary compatibility with existing implementations of that interface. Existing implementations inherit the default implementation.
This feature also enables C# to interoperate with APIs that target Android or Swift, which support similar features. Default interface methods also enable scenarios similar to a "traits" language feature.
B. Functional differences
There are still significant differences between an abstract class and an interface (even with default methods).
Here are a few things that an interface still cannot have/do while an abstract class can:
have a constructor,
keep state,
inherit from non abstract class,
have private methods.
C. Design
While default interface methods make interfaces even more powerful, abstract/base classes and interfaces still represent fundamentally different relationships.
(From When should I choose inheritance over an interface when designing C# class libraries?)
Inheritance describes an is-a relationship.
Implementing an interface describes a can-do relationship.
The only main difference coming to my mind is that you can still overload the default constructor for abstract classes which interfaces will never have.
abstract class LivingEntity
{
public int Health
{
get;
protected set;
}
protected LivingEntity(int health)
{
this.Health = health;
}
}
class Person : LivingEntity
{
public Person() : base(100)
{ }
}
class Dog : LivingEntity
{
public Dog() : base(50)
{ }
}
Two main differences:
Abstract classes can have state, but interfaces cannot.
A type can derive from a single abstract class, but can implement multiple interfaces.
There are some other, smaller, differences when it comes to default modifiers.

Default Interface Methods. What is deep meaningful difference now, between abstract class and interface?

I know that an abstract class is a special kind of class that cannot be instantiated. An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but, it cannot be instantiated. The advantage is that it can enforce certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.
Also I know that An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn’t support multiple inheritance, interfaces are used to implement multiple inheritance.
When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.
When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface.
BUT
BUT
BUT
I noticed that we will have Default Interface Methods in C# 8.0
Maybe I'm asking it because I have only 1-2 years of experience in programming, but what would be main difference between abstract class and interface now?
I know that we can't make state in interface, will it be only one difference between them?
Conceptual
First of all, there is a conceptual difference between a class and an interface.
A class should describe an "is a" relationship. E.g. a Ferrari is a Car
An interface should describe a contract of a type. E.g. A Car has a steering wheel.
Currently abstract classes are sometimes used for code reuse, even when there is no "is a" relationship. This pollutes the OO design. E.g. FerrariClass inherits from CarWithSteeringWheel
Benefits
So from above, you could reuse code without introducing a (conceptually wrong) abstract class.
You could inherit from multiple interfaces, while an abstract class is only single inheritance
There is co- and contravariance on interfaces and not on classes in C#
It's easier to implement an interface because some methods have default implementations. This could save a lot of work for an implementer of the interface, but the user won't see the difference :)
But most important for me (as I'm a library maintainer), you could add new methods to an interface without making a breaking change! Before C# 8, if an interface was publicly published, it should be fixed. Because changing the interface could break a lot.
The logger interface
This example shows some of the benefits.
You could describe a (oversimplified) logger interface as follows:
interface ILogger
{
void LogWarning(string message);
void LogError(string message);
void Log(LogLevel level, string message);
}
Then a user of that interface could log easily as warning and error using LogWarning and LogError. But the downside is that an implementer must implement all the methods.
An better interface with defaults would be:
interface ILogger
{
void LogWarning(string message) => Log(LogLevel.Warning, message);
void LogError(string message) => Log(LogLevel.Error, message);
void Log(LogLevel level, string message);
}
Now a user could still use all the methods, but the implementer only needs to implement Log. Also, he could implement LogWarning and LogError.
Also, in the future you might like to add the logLevel "Catastrophic". Before C#8 you could not add the method LogCatastrophic to ILogger without breaking all current implementations.
There is not a lot of difference between the two apart from the obvious fact that abstract classes can have state and interfaces cannot. Default methods or also known as virtual extension methods have actually been available in Java for a while. The main drive for default methods is interface evolution which means being able to add methods to an interface in future versions without breaking source or binary compatibility with existing implementations of that interface.
another couple of good points mentioned by this post:
The feature enables C# to interoperate with APIs targeting Android
(Java) and iOs (Swift), which support similar features.
As it turns out, adding default interface implementations provides
the elements of the "traits" language feature
(https://en.wikipedia.org/wiki/Trait_(computer_programming)). Traits
have proven to be a powerful programming technique
(http://scg.unibe.ch/archive/papers/Scha03aTraits.pdf).
Another thing which still makes the interface unique is covariance / contravariance.
To be honest, never found myself in situation where a default impl. in interface was the solution. I am a bit sceptical about it.
Both abstract classes and the new default interface methods have their appropriate uses.
A. Reasons
Default interface methods have not been introduced to substitute abstract classes.
What's new in C# 8.0 states:
This language feature enables API authors to add methods to an interface in later versions without breaking source or binary compatibility with existing implementations of that interface. Existing implementations inherit the default implementation.
This feature also enables C# to interoperate with APIs that target Android or Swift, which support similar features. Default interface methods also enable scenarios similar to a "traits" language feature.
B. Functional differences
There are still significant differences between an abstract class and an interface (even with default methods).
Here are a few things that an interface still cannot have/do while an abstract class can:
have a constructor,
keep state,
inherit from non abstract class,
have private methods.
C. Design
While default interface methods make interfaces even more powerful, abstract/base classes and interfaces still represent fundamentally different relationships.
(From When should I choose inheritance over an interface when designing C# class libraries?)
Inheritance describes an is-a relationship.
Implementing an interface describes a can-do relationship.
The only main difference coming to my mind is that you can still overload the default constructor for abstract classes which interfaces will never have.
abstract class LivingEntity
{
public int Health
{
get;
protected set;
}
protected LivingEntity(int health)
{
this.Health = health;
}
}
class Person : LivingEntity
{
public Person() : base(100)
{ }
}
class Dog : LivingEntity
{
public Dog() : base(50)
{ }
}
Two main differences:
Abstract classes can have state, but interfaces cannot.
A type can derive from a single abstract class, but can implement multiple interfaces.
There are some other, smaller, differences when it comes to default modifiers.

Is there any way to create a public .NET interface which can't be implemented outside of it's assembly?

In order to maintain binary backwards compatibility in .NET, you generally can't add new abstract methods to public classes and interfaces. If you do, then code built against the old version of the assembly that extends/implements your class/interface will fail at runtime because it fails to fully extend/implement the new version. For classes, however, there is a handy workaround:
public abstract class Foo {
internal Foo() { }
}
Because Foo's constructor is internal, no-one outside of my assembly can extend Foo. Thus, I can add new abstract methods to Foo without worrying about backward compatibility since I know that no class in another assembly can extend Foo.
My question is, is there a similar trick for interfaces? Can I create a public interface and somehow guarantee that no one outside of my assembly will be able to create an implementation of it?
No, you can't do that. But then, considering that the point of an interface is to define the behavior of an implementation by defining a contract, that makes sense.
What you can do, however, is create an internal interface that inherits from your public interface:
public interface IPublicInterface {
/* set-in-stone method definitions here */
}
internal interface IChildInterface : IPublicInterface {
/* add away! */
}
This should prevent any backwards compatibility issues with other assemblies while still allowing you to hide additional methods.
The downside, of course, is that you would have to remember to cast as IChildInterface when you need those, rather than simply being able to use it as an IPublicInterface
In all honesty, though, if you really wanted to define some assembly-only functionality while still requiring that the end user define their own implementations for some methods, then your best bet is probably an abstract class.
No, you can't.
But since in IL an interface is essentially just a pure abstract class (i.e. one without any implementation at all), you can use the technique you've already described and it will be practically the same.
As noted, keep in mind that this approach does restrict your type to inheriting just the fake "abstract class" interface. It can implement other interfaces, but won't be able to inherit any other type. This may or may not be a problem, depending on the scenario.
If it makes you feel better about the design, name your pure abstract class following the .NET convention for interfaces. E.g. IFoo instead of Foo.
Of course, it does imply the question: why do you want to do this? If you have no implementation at all, what harm could come from allowing other code to implement your interface?
But from a practical point of view, it's possible to enforce your rules the way you want.

What if you had an Abstract class with only abstract methods? How would that be different from an interface?

From my experience I think the following is true. If I am missing a major point please let me know.
Interface:
Every single Method declared in an Interface will have to be implemented in the subclass. Only Events, Delegates, Properties (C#) and Methods can exist in a Interface. A class can implement multiple Interfaces.
Abstract Class:
Only Abstract methods have to be implemented by the subclass. An Abstract class can have normal methods with implementations. Abstract class can also have class variables beside Events, Delegates, Properties and Methods. A class can only implement one abstract class only due non-existence of Multi-inheritance in C#.
So even that difference doesn't explain the question
1) What if you had an Abstract class with only abstract methods? How would that be different from an interface?
2) What if you had a Public variable inside the interface, how would that be different than in Abstract Class?
So any explanation will be vary help full.
Besides the technical differences it is mainly the intension of your design that should lead you to the decision to use one or the other:
Interfaces define the public API of the classes implementing them. Your goal of using an interface should be to show the usage of the classes that implement it. It is no side effect but a central design goal that a class can implement different interfaces to show the different roles it can act in.
An abstract class should implement some basic algorithm or common behaviour. It is mainly to join the common functionality of the subclasses in one place. Its purpose is to define the internal usage or flow and not the public interface. If you want to publish the usage of an abstract class it should implement a separate interface.
So:
1) An abstract class with only public abstract methods does not make any sense when you use the guidelines above. An abstract class can define protected abstract methods to define a flow or algorithm. But that is not possible with an interface.
2) Aditionally to the public properties abstract classes can define protected instance variables and therefor have many more usage scenarios (see explanation above).
EDIT: The "java" tag was removed by the author. I tried to make this as general as possible and it should be true for both java and C#
In Java:
An abstract class can implement an interface.
An interface cannot extend an abstract class.
BTW: Strangely - an abstract class can implement and interface without actually doing so.
interface I {
public String hello ();
}
interface J {
public String goodbye ();
}
abstract class A implements I, J {
#Override
abstract public String hello ();
}
class B extends A {
#Override
public String hello() {
return "Hello";
}
#Override
public String goodbye() {
return "goodbye";
}
}
All the variables of an Interface are by default public and static, you can not have a only public variable in an interface, whereas in an Abstract class you can declare a public variable.
If a class extends an Abstract class there is no any contract between them. Class which extends it may or may not override the abstract methods, however in case of interface there is a strict contract between the interface and the class that implements it, i.e the class will have to override all the method of that interface. So from the abstract method point of view they appears to be same, but are having completely different properties and advantages.
While your question indicates it's for "general OO", it really seems to be focusing on .NET use of these terms.
interfaces can have no state or implementation
a class that implements an interface must provide an implementation of all the methods of that interface
abstract classes may contain state (data members) and/or implementation (methods)
abstract classes can be inherited without implementing the abstract methods (though such a derived class is abstract itslef)
interfaces may be multiple-inherited, abstract classes may not (this is probably the key concrete reason for interfaces to exist separately from abtract classes - they permit an implementation of multiple inheritance that removes many of the problems of general MI).
As general OO terms, the differences are not necessarily well-defined. For example, there are C++ programmers who may hold similar rigid definitions (interfaces are a strict subset of abstract classes that cannot contain implementation), while some may say that an abstract class with some default implementations is still an interface or that a non-abstract class can still define an interface.
Indeed, there is a C++ idiom called the Non-Virtual Interface (NVI) where the public methods are non-virtual methods that 'thunk' to private virtual methods:
http://www.gotw.ca/publications/mill18.htm
http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Non-Virtual_Interface
What if you had an Abstract class with only abstract methods? How
would that be different from an interface?
You can implement multiple interfaces but extend only one class
Abstract class are more immune to changes then interface becuase if you change an interface it would break the class implementing it.
Interface can have only static final fields..Abstract class can have any type of fields.
interface don't have constructor but abstract class can have it
But java docs say this
If an abstract class contains only abstract method declarations, it
should be declared as an interface instead.
Even if all the methods in today's version of an abstract class are abstract, future version of the class could add virtual or non-virtual methods without forcing modifications to implementations nor recompilation of consumers. By contrast, adding any member to an interface will generally require all classes which implement the interface be modified to implement that member, and both implementations and consumers will generally have to be recompiled regardless of whether the change added anything that wasn't already implemented.
The fact that abstract changes may be changed without breaking implementations or consumers is a big advantage in favor of abstract classes. On the other hand, an abstract class will force any implementing class to derive from it alone and no other class. By contrast, an interface will pose almost restrictions on what its implementers are allowed to inherit or derive from. That is a big advantage in favor of interfaces.
Because abstract classes and interfaces each have definite advantages, there are times when either may be better than the other. Conceptually, it would be possible to add a couple features to the way interfaces work that would give them the advantages presently enjoyed only by abstract classes, but I know of no particular plans to do so.
Your class can extends only one abstract class and implements many interfaces.
Well, in an abstract class you could also have fields, and auto-properties wouldn't need to be reimplemented. You can also specify access specifiers that aren't public. Also, it has better scalability (e.g. you can use [Obsolete] to mark an old implementation, and then make the new one call the old one by default). Also, it would stop you from having any more inheritance of classes. Another thing is that you can set static fields in abstract classes.
Also, interfaces are usually something that performs an action, while classes are about being that.
*1) What if you had an Abstract class with only abstract methods? How would that be different from an interface?*
By default the methods in an interface are 'public abstract' and the abstract class will also have the abstract methods as 'public abstract'.
If the abstract class contains only abstracts methods then it's better to make it an interface.
*2) What if you had a Public variable inside the interface, how would that be different than in Abstract Class?*
Interfaces can't have variables. If you meant properties, events, delegates etc... they would be by default 'Public'. If nothing is specified in the abstract class it would be 'Private'(In regards to members of the interface/abstract class only).
An interface is used when you want your class to be able to do something.
Your class extends an abstract class when there is a 'is a' relationship.
There is a semantic difference.
In case of abstract class.
class Dog : abstractAnimal
When we create object of Dog, we will have to create object of abstractAnimal to, it will lead to extra object creation.
In case of interface.
class Dog : IAnimal
When we create object of Dog, we will not be creating any extra object of anything.
In that case you can say:
1) We can specify different access modifier to methods present in class,
but we can't change access modifier of Interface member.
2) Derived class from abstract will not have a compulsion of
implementation.

Difference between Interface and Abstract class in terms of Decoupling?

As we know there are basically two important difference between Interface and Abstract class.
We can have function definitions in abstract class. This is advantageous when we want to add a function in a class without need to track down it's all implementations.
We can have multiple interface implementation.
I just came to know that we can differentiate between them in terms of Decoupling?
Your comments...
Also if you can you provide a very basic link that explains the Decoupling for Interface and Abstract class ?
We normally use Business Logic Layer, Data Access Layer(contains abstract functions) and DataAccess.SqlServer Layer. Right? Despite of the fact that we aware of the Business needs, why are we creating Data Access Layer(contains abstract functions), Why can't Business Logic layer directly access DataAccess.SqlServer Layer?
Decoupling
In programming and design, this is generally the act of making code which is re-usable with as few dependencies as possible.
Factory Pattern In This Context
When using the Factory Pattern, you have a centralized factory which can create objects without necessarily defining them itself. That would be up to the object's definition.
Abstract and Interface
Interface
Defining an interface is best practice, as it allows for a light weight type to be used for inference, and also provides a blueprint which all inheriting classes must abide by. For example, IDisposable must implement the Dispose method. Note that this is decoupled from the interface, as each class inheriting IDisposable will define its own function of the Dispose method.
Abstract
Abstract is similar to interface in that it is used for inheritance and inference, but it contains definitions which all classes will inherit. Something to the extent of every automobile will have an engine so a good abstract class for automobile could include a predefined set of methods for an engine.
Edit
Explanation
Here you will see a simple example of inheritance using an interface and an abstract class. The decoupling occurs when the interface is inherited by an abstract class and then it's methods are customized. This allows for a class to inherit the abstract class and still have the same type as the interface. The advantage is that the class inheriting the abstract class can be used when the expected type is the original interface.
Decoupling
That advantage allows for any implementation to be used which conforms to the expected interface. As such, many different overloads can be written and passed in. Here is an example of one.
Example
Interface Definition
public interface IReady
{
bool ComputeReadiness();
}
Inheritance
public abstract class WidgetExample : IReady
{
public int WidgetCount { get; set; }
public int WidgetTarget { get; set; }
public bool WidgetsReady { get; set; }
public WidgetExample()
{
WidgetCount = 3;
WidgetTarget = 45;
}
public bool ComputeReadiness()
{
if (WidgetCount < WidgetTarget)
{
WidgetsReady = false;
}
return WidgetsReady;
}
}
public class Foo : WidgetExample
{
public Foo()
{
this.WidgetTarget = 2;
}
}
public class Bar : IReady
{
public bool ComputeReadiness()
{
return true;
}
}
Decoupling
public class UsesIReady
{
public bool Start { get; set; }
public List<string> WidgetNames { get; set; }
//Here is the decoupling. Note that any object passed
//in with type IReady will be accepted in this method
public void BeginWork(IReady readiness)
{
if (readiness.ComputeReadiness())
{
Start = true;
Work();
}
}
private void Work()
{
foreach( var name in WidgetNames )
{
//todo: build name
}
}
}
Polymorphism
public class Main
{
public Main()
{
//Notice that either one of these implementations
//is accepted by BeginWork
//Foo uses the abstract class
IReady example = new Foo();
UsesIReady workExample = new UsesIReady();
workExample.BeginWork(example);
//Bar uses the interface
IReady sample = new Bar();
UsesIReady workSample = new UsesIReady();
workSample.BeginWork(sample);
}
}
I've been looking through the answers, and they all seem a little complicated for the question. So here is my (hopefully) simpler answer.
Interface should be used when none of the implementation details are available to the current scope of the code.
Abstracts should be used when some of the implementation details are available to you
And, for completeness, when all of the implementation details are available you should be using classes.
In terms of decoupling, while I somewhat agree with Shelakel, for the purposes of this question, and stating fully decoupled design practices, I would suggest the following:
Always use Interfaces to define external behaviour.
When you have some of the implementation details available, use
abstract classes to define them, but implement the interfaces on
the abstract classes, and inherit from those classes in turn.
This ensures that later if you need to change some obscure implementation detail in a new implementation you are able to do so without modifying the existing abstract class, and are also able to group different implementation types into different abstract classes.
EDIT: I forgot to include the link :)
http://www.codeproject.com/Articles/11155/Abstract-Class-versus-Interface
Abstract classes and interfaces are not MUTUALLY EXCLUSIVE choices. I often define both an Interface and an abstract class that implements that interface.
The interface ensure the maximum decoupling because it doesnt force your class to belong to a specific inheritance hierarchy, so your class may inherit from whichever other class. In other terms any class can inherit from an Interface, while classes that already inherits from other classes cannot inherit from an abstract class.
On the other side in an abstract class you can factor out code that is common to all implementations, while with Interfaces you are forced to implement everything from the scratch.
As a conclusion, often the best solution is using BOTH an abstract class and an Interface, so one can move from re-using the common code contained in the abstract class, if possible, to re-implementing the interface from the scratch, if needed.
Decoupling for the sake of decoupling is a futile exercise.
Interfaces are meant to be used for integration where the specifics aren't required to be known to be of use (ex. SendEmail()). Common uses include components, services, repositories and as markers for IOC and generic implementations.
Extension methods with generic type constraints that include interfaces allow functionality similar to traits found in Scala with similar composability.
public interface IHasQuantity { double Quantity { get; } }
public interface IHasPrice { decimal PricePerUnit { get; } }
public static class TraitExtensions
{
public static decimal CalculateTotalPrice<T>(this T instance)
where T : class, IHasPrice, IHasQuantity
{
return (decimal)instance.Quantity * instance.PricePerQuantity;
}
}
In my opinion, abstract classes and class inheritance is overused.
SOLID design principles teach us that Liskov's substitution principle implies that class inheritance should only be used if the inherited class is substitutable for the ancestor. This means that all methods should be implemented (no throw new NotImplementedExeption()) and should behave as expected.
I personally have found class inheritance useful in the case of the Template Method pattern as well as for state machines. Design patterns such as the builder pattern are in most cases more useful than deep chains of inheritance.
Now back to your question; interfaces should be used most if not all of the time. Class inheritance should be used internally and only externally for purposes of definition, whereafter an interface should be used for interaction and the concrete implementation provided via a factory or to be injected via an IOC container.
Ideally when using external libraries, an interface should be created and an adapter implemented to expose only the functionality required. Most of these components allow to be configured beforehand or at runtime to be resolved via an IOC container.
In terms of decoupling, it is important to decouple the application from its implementations (especially external dependencies) to minimize the reasons to change.
I hope that my explanation points you in the right direction. Remember that it's preferred to refactor working implementations and thereafter interfaces are defined to expose functionality.
I'm not going to discuss what are the pros/cons of these two constructs in general, as there are enough resources on that.
However, In terms of 'decoupling' a component from another, interface inheritance is much better than abstract classes, or class inheritance in general (In fact I don't think being abstract or not does not make much difference in terms of decoupling as all abstract does is prevent the class being instantiated without a concrete implementation).
Reason for above argument is, interfaces allow you to narrow down the exposure to absolute minimum of what required by the 'dependent component', if it requires a single method interface can easily do that, or even be a marker interface without any method. This might be difficult with a base class (abstract or concrete) as it should implement all the 'common' functionality for that base. Because of this a component dependent on the 'base type' will automatically 'see' all the common functionality even it does not need them for it's purposes.
Interfaces also gives you the best flexibility as even classes inheriting from bases which have nothing in common, can still implement an interface, and be used by the component expecting that interface. Good example of this is IDisposable interface.
So, my conclusion is for decoupling concern have all your components depend on interfaces than base types, and if you find most of your classes implementing that interface has a common implementation then have a base class implementing that interface and inherit other classes from that base.
The core difference is this:
Interfaces expose zero or more method signatures which all descendants must in turn implement (otherwise code won't even compile).
Interface-exposed methods can either be implemented implicitly (every type derived from the interface has access to them) or explicitely (methods can be accessed only if you typecast the object to the interface type itself). More details and an example can be found in this question.
Abstract classes expose zero or more full-fledged methods, which descendants can either use or override, providing their own implementation. This approach allows you to define a customizable, "default" behavior. Abstract classes allows you to easily add new methods with no issues (NotImplementedException really shines when adding methods to abstract classes), whereas adding a method to an interface requires you to modify all the classes implementing it.
The final point is, that a class can implement more than one interface simultaneously.
Some real-world example might be:
A hard drive which provides both USB and LAN ports is a good demonstration of multiple interface inheritance
A Laptop which has a LED marked "bluetooth" but no bluetooth hardware on board is a good analogy of the concept of not implementing an abstract method (you have the LED, you have the little B symbol, but there's nothing under the roof).
Edit 1
Here's a MSDN link explaining how to choose between interface and classes.
Defining a contract using an abstract class means that your implementers must inherit from this abstract class. Since C# doesn't support multiple inheritance, these implementers will not be able to have an alternate class hierarchy, which can be pretty limiting for some. In other words, an abstract class basically otherwise robs the implementer of the class hierarchy feature, which is often needed to get or use some other capabilities (of a framework or class library).
Defining a contract using an interface leaves the class hierarchy free for your implementers to use any way they see fit, in other words, providing much more freedom of implementation.
From a perspective of evaluation criteria, when we talk about coupling here we can speak to concerns of three separable authors, the client using (calling) the API/contract, the definer of the API/contract, and the implementer of the API/contract; we can speak to freedom (the fewer restrictions, the better), encapsulation (the less awareness necessary, the better), and resilience in the face of change.
I would offer that an interface results in looser coupling than an abstract class, in particular, between the definer and the implementer, due to higher freedom offered the implementer.
On the other hand, when it comes to versioning, you can at least add another method to the abstract class without necessarily requiring updates to subclass implementations, provided the added method has an implementation in the abstract class. Versioning interfaces across DLL boundaries usually means adding another interface, much more complex to roll out. (Of course, this is not a concern if you can refactor all the implementations together (say, because they're all in the same DLL)).
The best way to understand and remember difference between interface and abstract class, it's to remember that abstract class is a normal class and you can do everything with abstract class that you can do with the normal class with two exceptions.
You can't instantiate an abstract class
You can have abstract method only in abstract class
Coding to interface provides reusability and polymorphism.As far as class implements interface,the interface or abstract class can be passed to parameter instead of class that implements the interface.Urs common technical problem is handled vis designing interface and abstract class and implementing it and giving subclass the specific functionality implementation.Imagine its like framework.Framework define interface and abstract class and implement it that is common to all.And those that are abstract is implemented by client according to its own requirement.
public interface Polymorphism{
void run();
Void Bark();
Energy getEnergy(Polymorphism test);
Public abstract class EnergySynthesis implements Polymorphism{
abstract void Energy();
Void Bark(){
getEnergy(){
}
void run(){
getEnergy();
}public EnegyGeneartion extends EnergySynthesis {
Energy getEnergy(Polymorphism test){
return new Energy( test);
}
MainClass{
EnegyGeneartion test=new EnegyGeneartion ();
test.getEnergy(test);
test.Bark()
.
.
.
.
.
//here in Energy getEnergy(Polymorphism test) any class can be passed as parameter that implemets interface

Categories

Resources