Difference between Interface and Abstract class in terms of Decoupling? - c#

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

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.

Interface / Abstract Class Coding Standard

I spotted a proposed C# coding-standard which stated "Try to offer an interface with all abstract classes". Does someone know the rationale for this?
The .NET Framework Design Guidelines have some interesting things to say about interfaces and abstract classes.
In particular, they note that interfaces have the major drawback of being less flexible than classes when it comes to the evolution of an API. Once you ship an interface, its members are fixed forever, and any additions will break compatibility with the existing types that implement that interface. Whereas, shipping a class offers much more flexibility. Members can be added at any time, even after the initial version has shipped, as long as they are not abstract. Any existing derived classes can continue to work unchanged. The System.IO.Stream abstract class provided in the Framework is given as an example. It initially shipped without support for timing out pending I/O operations, but version 2.0 was able to add members that supported this feature, even from existing subclasses.
Thus, having a corresponding interface for each abstract base class provides few additional benefits. The interface cannot be publically exposed, or you're left back at square one in terms of versioning. And if you only expose the abstract base class, there's little gained by having the interface in the first place.
Additionally, the point is often made in favor of interfaces that they allow separating contract from implementation. Krzysztof Cwalina argues that this claim is specious: it incorrectly assumes you cannot separate contracts from implementation using classes. By writing abstract classes that reside in a separate assembly from their concrete implementations, it's easy to achieve the same virtues of separation. He writes:
I often hear people saying that interfaces specify contracts. I believe this is a dangerous myth. Interfaces, by themselves, do not specify much beyond the syntax required to use an object. The interface-as-contract myth causes people to do the wrong thing when trying to separate contracts from implementation, which is a great engineering practice. Interfaces separate syntax from implementation, which is not that useful, and the myth provides a false sense of doing the right engineering. In reality, the contract is semantics, and these can actually be nicely expressed with some implementation.
In general, the guideline provided is DO favor defining classes over interfaces. Again, Krzysztof comments:
Over the course of the three versions of the .NET Framework, I have talked about this guideline with quite a few developers on our team. Many of them, including those who initially disagreed with the guideline, have said that they regret having shipped some API as an interface. I have not heard of even one case in which somebody regretted that they shipped a class.
A second guideline argues that one DO use abstract classes instead of interfaces to decouple the contract from implementations. The point here is that correctly-designed abstract classes still allow for the same degree of decoupling between contract and implementation as interfaces. Brian Pepin's personal perspective is thus:
One thing I've started doing is to actually bake as much contract into my abstract class as possible. For example, I might want to have four overloads to a method where each overload offers an increasingly complex set of parameters. The best way to do this is to provide a nonvirtual implementation of these methods on the abstract class, and have the implementations all route to a protected abstract method that provides the actual implementation. By doing this, you can write all the boring argument-checking logic once. Developers who want to implement your class will thank you.
Perhaps one would do best by revisiting the oft-touted "rule" that a derived class indicates an IS-A relationship with the base class, whereas a class implementing an interface has a CAN-DO relationship with that interface. To make the claim one should always code both an interface and an abstract base class, independent of specific reasons to do so, seems to miss the point.
Without looking at the original article, I would guess that the original author is suggesting it for testability and allow easy mocking of the class with tools like MoQ, RhinoMocks etc.
I always understood Interface-Driven Design (IDD) to involve the following steps in creating a concrete class (in its purest form, for non-trivial classes):
Create an interface to describe the properties and behaviours your objects must exhibit, but not how those should function.
Create an abstract base class as the primary implementation of the interface. Implement any functionality required by the interface, but which is unlikely to differ between concrete implementations. Also provide appropriate default (virtual) implementations for members which are unlikely (but possible) to change. You can also provide appropriate constructors (something not possible at the interface level). Mark all other interface members as abstract.
Create your concrete class from the abstract class, overriding a subset of the members originally defined by the interface.
The above process, while long-winded, ensures maximum adherence to the contract you initially lay down, while minimising redundant code in alternative implementations.
This is why I would generally pair an abstract class with an interface.
I think it's premature to say whether an interface is needed or not in a general sense. So, I think we should not put "Try to offer an interface with all abstract classes" as a coding standard unless that coding standard includes more details on when this rule applies.
If I am not going to use the interface at all, am I still required to define an interface just to fulfill the coding standard?
Test-driven development (TDD) is one key reason why you would want to do this. If you have a class that depends directly on your abstract class you cannot test it without writing a subclass that can be instantiated in your unit tests. If, however, your dependent class only depends on an interface then you can provide an 'instance' of this easily using a mocking framework such as Rhino Mocks, NMock, etc.
Ultimately I think it's going to be down to how you ship your product. We only ever ship binaries and customers never extend our work. Internally we have interfaces for pretty much everything so classes can be isolated completely for unit testing. This offers huge benefits for refactoring and regression testing!
EDIT: updated with example
Consider following code in a unit test:
// doesn't work - can't instantiate BaseClass directly
var target = new ClassForTesting(new BaseClass());
// where we only rely on interface can easily generate mock in our tests
var targetWithInterface = new ClassForTestingWithInterface(MockRepository.GenerateStub<ISomeInterface>());
where the abstract class version is:
// dependent class using an abstract class
public abstract class BaseClass
{
public abstract void SomeMethod();
}
public class ClassForTesting
{
public BaseClass SomeMember { get; private set; }
public ClassForTesting(BaseClass baseClass)
{
if (baseClass == null) throw new ArgumentNullException("baseClass");
SomeMember = baseClass;
}
}
and the same stuff but using interface is:
public interface ISomeInterface
{
void SomeMethod();
}
public abstract class BaseClassWithInterface : ISomeInterface
{
public abstract void SomeMethod();
}
public class ClassForTestingWithInterface
{
public ISomeInterface SomeMember { get; private set; }
public ClassForTestingWithInterface(ISomeInterface baseClass) {...}
}

Interface or abstract class?

For my new Pet-Project I have a question for design, that is decided already, but I want some other opinions on that too.
I have two classes (simplified):
class MyObject
{
string name {get;set;}
enum relation {get;set;}
int value {get;set;}
}
class MyObjectGroup
{
string name {get;set;}
enum relation {get;set;}
int value {get;set;}
List<MyObject> myobjects {get;set;}
}
Later in the Project MyObjectGroup and MyObject should be used equally. For this I could go two ways:
Create an interface: IObject
Create an abstract class: ObjectBase
I decided to go the way of the interface, that I later in code must not write ObjectBase every time but IObject just for ease - but what are other positives for this way?
And second, what about adding IXmlSerializable to the whole story?
Let the interface inherit from IXmlSerializable or does it have more positives to implement IXmlSerializable in abstract base class?
Generally speaking, the approach I use in this kind of situation is to have both an interface and an abstract class. The interfaces defines, well, the interface. The abstract class is merely a helper.
You really can't go wrong with this approach. Interfaces give you the flexibility to change implementation. Abstract classes give you boilerplate and helper code that you aren't forced to use, which you otherwise would be if your methods were defined in terms of an abstract class explicitly.
These are some of the differences between Interfaces and Abstract classes.
1A. A class may inherit (Implement) one or more interfaces. So in C#, interfaces are used to achieve multiple inheritance.
1B. A class may inherit only one abstract class.
2A. An interface cannot provide any code, just the signature.
2B. An abstract class can provide complete, default code and/or just the details that have to be overridden.
3A. An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public.
3B. An abstract class can contain access modifiers for the subs, functions, properties.
4A. Interfaces are used to define the peripheral abilities of a class. For eg. A Ship and a Car can implement a IMovable interface.
4B. An abstract class defines the core identity of a class and there it is used for objects.
5A. If various implementations only share method signatures then it is better to use Interfaces.
5B. If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.
6A. If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.
6B. If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
7A. An interface can not have fields defined.
7B. An abstract class can have fields and constants defined.
8A. An interface can not have constructor.
8B. An abstract class can have default constructors implemented.
9A. An interface can only inherit from other interfaces.
9B. An abstract class can inherit from interfaces, abstract class, or even class.
The interface would be my default until there is a reason to use a base class, as it makes fewer decisions for us.
I wouldn't involve IXmlSerializable unless I had to though; it is a messy, tricky interface that is often a cause of woe.
What exactly are your serialization requirements? There may be better options... however, for many serializers a base-class would be easier than an interface. For example, for XmlSerializer you could have:
[XmlInclude(typeof(MyObject))] // : ObjectBase
[XmlInclude(typeof(MyObjectGroup))] // : ObjectBase
public abstract class ObjectBase { /* */ }
(the exact approach depends on the serializer)
Generally, you should consider interfaces as contracts that some types implement and abstract classes as nodes in inheritance hierarchy that don't exist by themselves (i.e. there is an "is a" relationship between the derived class and the base abstract class). However, in practice, you might need to use interfaces in other cases, like when you need multiple inheritance.
For instance, IXmlSerializable is not an "entity" by itself. It defines a contract that an entity can implement. Interfaces live "outside" the inheritance hierarchy.
An Interface will allow you to define a 'contract' that the object will need to fulfil by delivering properties and methods as described by the interface. You can refer to objects by variables of interface-type which can cause some confusion as to what exactly is being offered.
A base class offers the opportunity to build an inheritance 'tree' where more complex classes (of a common 'type') are built on the foundations of a simpler 'base' classes. The classic and annoying example in OO is normally a base class of 'Shape' and which is inherited by Triangle, Square, etc.
The main point is that with an Interface you need to provide the entire contract with every class that implements it, with an inheritance tree (base classes) you are only changing/adding the properties and methods that are unique to the child class, common properties and methods remain in the base class.
In your example above I'd have the 'MyObjectGroup' object inherit the base 'MyObject' class, nothing to be gained from an interface here that I can see.
There are two thing is in Architect’s mind when designing classes.
Behavior of an object.
object’s implementation.
If an entity has more than one implementation, then separating the behavior of an object from its implementation is one of the key for maintainability and decoupling.
Separation can be achieved by either Abstract class or Interface but which one is the best? Lets take an example to check this.
Lets take a development scenario where things (request, class model, etc) are changing very frequently and you have to deliver certain versions of application.
Initial problem statement : you have to create a “Train” class for Indian railway which has behavior of maxSpeed in 1970 .
1. Business Modeling with abstract class
V 0.0 (Initial problem)
Initial problem statement : you have to create a Train class for Indian railway which has behavior of maxSpeed in 1970 .
public abstract class Train {
public int maxSpeed();
}
V 1.0 (Changed problem 1)
changed problem statement : You have to create a Diesel Train class for Indian railway which has behavior of maxSpeed, in 1975.
public abstract class DieselTrain extends train {
public int maxFuelCapacity ();
}
V 2.0 (Changed problem 2)
chanded problem statement : you have to create a ElectricalTrain class for Indian railway which has behavior of maxSpeed , maxVoltage in 1980.
public abstract class ElectricalTrain extends train {
public int maxvoltage ();
}
V 3.0 (Changed problem 3 )
chanded problem statement : you have to create a HybridTrain (uses both diesel and electrcity) class for Indian railway which has behavior of maxSpeed , maxVoltage,maxVoltage in 1985 .
public abstract class HybridTrain extends ElectricalTrain , DisealTrain {
{ Not possible in java }
}
{here Business modeling with abstract class fails}
2. Business Modeling with interface
Just change abstract word to interface and ……
your Business Modeling with interface will succeeds.
http://javaqna.wordpress.com/2008/08/24/why-the-use-on-interfaces-instead-of-abstract-classes-is-encouraged-in-java-programming/
Interface:
If your child classes should all implement a certain group of methods/functionalities but each of the child classes is free to provide its own implementation then use interfaces.
For e.g. if you are implementing a class hierarchy for vehicles implement an interface called Vehicle which has properties like Colour MaxSpeed etc. and methods like Drive(). All child classes like Car Scooter AirPlane SolarCar etc. should derive from this base interface but provide a seperate implementation of the methods and properties exposed by Vehicle.
–> If you want your child classes to implement multiple unrelated functionalities in short multiple inheritance use interfaces.
For e.g. if you are implementing a class called SpaceShip that has to have functionalities from a Vehicle as well as that from a UFO then make both Vehicle and UFO as interfaces and then create a class SpaceShip that implements both Vehicle and UFO .
Abstract Classes:
–> When you have a requirement where your base class should provide default implementation of certain methods whereas other methods should be open to being overridden by child classes use abstract classes.
For e.g. again take the example of the Vehicle class above. If we want all classes deriving from Vehicle to implement the Drive() method in a fixed way whereas the other methods can be overridden by child classes. In such a scenario we implement the Vehicle class as an abstract class with an implementation of Drive while leave the other methods / properties as abstract so they could be overridden by child classes.
–> The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.
For example a class library may define an abstract class that is used as a parameter to many of its functions and require programmers using that library to provide their own implementation of the class by creating a derived class.
You could actually go with BOTH. ObjectBase saves you the trouble of implementing the common properties more than once and implements IObject for you. Everywhere you use it refer to IObject so you can do testing with mocks later
I'd rather go for base abstract class, because, theoretically (well, it's just one theory, I'm not proving or saying that any other is worse then this) - interfaces should be used, when you want to show, that some object is capable of doing something (like IComparable - you show that whatever implements it, can be compared to something else), whereas when you have 2 instances that just share something common or have 1 logical parent - abstract classes should be used.
You could also go for both approaches, using base class, that will implement an interface, that will explicitly point what your class can do.
Note that you cannot override operators in Interfaces. That is the only real problem with them as far as I'm concerned.
All else being equal, go with the interface. Easier to mock out for unit testing.
But generally, all I use base classes for is when there's some common code that I'd rather put in one place, rather than each instance of the derived class. If it's for something like what you're describing, where the way they're used is the same, but their underlying mechanics are different, an interface sounds more appropriate.
I've been using abstract classes in my projects, but in future projects, I'll use interfaces.
The advantage of "multiple inheritance" is extremely useful.
Having the ability to provide a completely new implementation of the class, both in code, or for testing purposes, is always welcome.
Lastly, if in the future you'll want to have the ability to customize your code by external developers, you don't have to give them your real code - they can just use the interfaces...
If you have function in class,you should use abstact class instead of interface.
In general,an interface is used to be on behalf of a type.
Choosing interfaces and abstract classes is not an either/or proposition. If you need to change your design, make it an interface. However, you may have abstract classes that provide some default behavior. Abstract classes are excellent candidates inside of application frameworks.
Abstract classes let you define some behaviors; they force your subclasses to provide others. For example, if you have an application framework, an abstract class may provide default services such as event and message handling. Those services allow your application to plug in to your application framework. However, there is some application-specific functionality that only your application can perform. Such functionality might include startup and shutdown tasks, which are often application-dependent. So instead of trying to define that behavior itself, the abstract base class can declare abstract shutdown and startup methods. The base class knows that it needs those methods, but an abstract class lets your class admit that it doesn't know how to perform those actions; it only knows that it must initiate the actions. When it is time to start up, the abstract class can call the startup method. When the base class calls this method, Java calls the method defined by the child class.
Many developers forget that a class that defines an abstract method can call that method as well. Abstract classes are an excellent way to create planned inheritance hierarchies. They're also a good choice for nonleaf classes in class hierarchies.
The definition of the abstract class may describe code and state, and classes that derive from them may not derive from other classes at the same time. That's what the technical difference is.
Therefore, from the point of view of usage & philosophy, the difference is that by setting up an abstract class, you constrain any other functionality that the objects of that class may implement, and provide those objects with some basic functionality that is common for any such object (which is a kind of constraint, too), while by setting up an interface, you set up no constraints for other functionality and make no real-code provisions for that functionality which you have in mind. Use the abstract classes when you about know everything that objects of this class are supposed to be doing for the benefit of their users. Use the interfaces when the objects might also do something else that you can't even guess by now.

Why do both the abstract class and interface exist in C#?

Why do both the abstract class and interface exist in C# if we can achieve the interface feature by making all the members in the class as abstract.
Is it because:
Interface exists to have multiple inheritance
It makes sense to have interface because object's CAN-DO feature should be placed in an interface rather base abstract class.
Please clarify
Well, an abstract class can specify some implemetation, but usually not all of it. (Having said which, it's perfectly possible to provide an abstract class with no abstract members, but plenty of virtual ones which with "no-op" implementations). An interface provides no implementation, merely a contract.
You could certainly argue that if multiple inheritance of classes were permitted, interfaces would be largely pointless.
Personally I don't get hung up on the whole "is-a" vs "can-do" distinction for inheritance. It never gives me as good an intuition about what to do as just playing around with different ideas and seeing which ones feel the most flexible. (Then again, I'm very much a "favour composition over inheritance" guy...)
EDIT: Just as the most convenient way of rebutting lbushkin's third point in his comment... you can override an abstract method with a non-virtual one (in terms of not being able to override it further) by sealing it:
public abstract class AbstractBase
{
public abstract void Foo();
}
public class Derived : AbstractBase
{
public sealed override void Foo() {}
}
Classes deriving from Derived cannot override Foo any further.
I'm not in any way suggesting I want multiple inheritance of implementation - but if we did have it (along with its complexity) then an abstract class which just contained abstract methods would accomplish almost everything that an interface does. (There's the matter of explicit interface implementation, but that's all I can think of at the moment.)
It's not a trivial question, it's a very good question and one I always ask any candidates I interview.
In a nutshell - an abstract base class defines a type hierarchy whereas an interface defines a contract.
You can see it as is a vs implements a.
i.e
Account could be an abstract base account because you could have a CheckingAccount, a SavingsAccount, etc all which derive from the abstract base class Account. Abstract base classes may also contain non abstract methods, properties and fields just like any normal class. However interfaces only contain abstract methods and properties that must be implemented.
c# let's you derive from one base class only - single inheritance just like java. However you can implement as many interfaces as you like - this is because an interface is just a contract which your class promises to implement.
So if I had a class SourceFile then my class could choose to implement ISourceControl which says 'I faithfully promise to implement the methods and properties that ISourceControl requires'
This is a big area and probably worthy of a better post than the one I've given however I'm short on time but I hope that helps!
They both exist because they are both very different things. Abstract classes permit implementation and interfaces do not. An interface is very handy as it allows me to to say something about the type I am building (it is serializable, it is edible, etc.) but it does not allow me to define any implementation for the members I define.
An abstract class is more powerful that an interface in the sense that it allows me to create an inheritance interface via abstract and virtual members but also provide some sort of default or base implementation if I so choose. As Spiderman knows, however, with that great power comes great responsibility as an abstract class is more architecturally brittle.
Side Note: Something interesting to note is that Vance Morrrison (of the CLR team) has speculated about adding default method implementations to interfaces in a future version of the CLR. This would greatly blur the distinction between an interface and an abstract class. See this video for details.
One important reason both mechanisms exist because c#.NET only allows single inheritance, not multiple inheritance like C++. The class inheritance allows you to inherit implementation from only one place; everything else must be accomplished by implementing interfaces.
For example, let's suppose I create a class, like Car and I subclass into three subclasses, RearWheelDrive, FrontWheelDrive, and AllWheelDrive. Now I decide that I need to cut my classes along a different "axis," like those with push-button starters and those without. I want all pushbutton start cars to have a "PushStartButton()" method and non-pushbutton cars to have a "TurnKey()" method and I want to be able to treat Car objects (with regard to starting them) irrespective of which subclass they are. I can define interfaces that my classes can implement, such as IPushButtonStart and IKeyedIgnition, so I have a common way to deal with my objects that differ in a way that is independent of the single base class from which each derives.
You gave a good answer already. I think your second answer is the real reason. If I wanted to make an object Compareable I shouldn't have to derive from a Comparable base class. if you think of all the interfaces think of all the permutations you'd beed to handle the basic interfaces like IComparable.
Interfaces let us define a contract around the publicly exposed behavior an object provides. Abstract classes let you define both behavior and implementation, which is a very different thing.
Interfaces exist to provide a class without any implementation whatsoever, so that .NET can provide support for safe and functional multiple inheritance in a managed environment.
An Interface defines a contract that an implementing class must fulfil; it is a way of stating that "this does that". An Abstract Class is a partial implementation of a class which is by definition incomplete, and which needs a derviation to be completed. They're very different things.
An abstract class can have an implementation while an interface just allows you to create a contract that implementers have to follow. With abstract classes you can provide a common behavior to their sub classes witch you can't with interfaces.
They serve two distinctly different purposes.
Abstract classes provide a way to have a an object inherit from a defined contract, as well as allowing behavior to be specified in the base class. This, from a theoretical standpoint, provides an IS-A relationship, in that the concrete class IS-A specific type of the base class.
Interfaces allow classes to define a (or more than one) contract which they will fulfill. They allow for a ACTS-AS or "can be used as an" type of relationship, as opposed to direct inheritance. This is why, typically, interfaces will use an adjective as they're name (IDisposable) instead of a noun.
An interface is used for what a class can do, but it is also used to hide some of things that a class can do.
For example the IEnumerable<T> interface describes that a class can iterate through it's members, but it's also limits the access to this single ability. A List<T> can also access the items by index, but when you access it through the IEnumerable<T> interface, you only know about it's ability to iterate the members.
If a method accepts the IEnumerable<T> interface as a parameter, that means that it's only interrested in the ability to iterate through the members. You can use several different classes with this ability (like a List<T> or an array T[]) without the need for one method for each class.
Not only can a method accept several different classes that implement an interface, you can create new classes that implement the interface and the method will happily accept those too.
The idea is simple - if your class(YourClass) is already deriving from a parent class(SomeParentClass) and at the same time you want your class(YourClass) to have a new behavior that is defined in some abstract class(SomeAbstractClass), you can't do that by simply deriving from that abstract class(SomeAbstractClass), C# doesn't allow multiple inheritance.
However if your new behavior was instead defined in an interface (IYourInterface), you could easily derive from the interface(IYourInterface) along with parent class(SomeParentClass).
Consider having a class Fruit that is derived by two children(Apple & Banana) as shown below:
class Fruit
{
public virtual string GetColor()
{
return string.Empty;
}
}
class Apple : Fruit
{
public override string GetColor()
{
return "Red";
}
}
class Banana : Fruit
{
public override string GetColor()
{
return "Yellow";
}
}
We have an existing interface ICloneable in C#. This interface has a single method as shown below, a class that implements this interface guarantees that it can be cloned:
public interface ICloneable
{
object Clone();
}
Now if I want to make my Apple class(not Banana class) clonable, I can simpley implement ICloneable like this:
class Apple : Fruit , ICloneable
{
public object Clone()
{
// add your code here
}
public override string GetColor()
{
return "Red";
}
}
Now considering your argument of pure abstract class, if C# had a pure abstract class say Clonable instead of interface IClonable like this:
abstract class Clonable
{
public abstract object Clone();
}
Could you now make your Apple class clonable by inheriting the abstract Clonable instead of IClonable? like this:
// Error: Class 'Apple' cannot have multiple base classes: 'Fruit' & 'Clonable'
class Apple : Fruit, Clonable
{
public object Clone()
{
// add your code here
}
public override string GetColor()
{
return "Red";
}
}
No, you can't, because a class cannot derive from multiple classes.

Categories

Resources