Why use interface and abstract over just abstract? - c#

I'm reading some code online where someone implemented the following classes: IMapObj which is a normal interface, AbstractMapObj that derives from that interface and a lot of map objects that derive from AbstrsctMapObj.
Throughout all his code, he refers to IMapObj and not AbstractMapObj.
What's the benefit of using an interface and an abstract class instead of just an abstract class? Needless to say no other class derives from IMapObj, only AbstractMapObj.

There is only 1 reason to use both, and that is that the abstract class can provide a default implementation of some or all of the functionality. The interface can be easily mocked for testing.

What's the benefit of using an interface and an abstract class instead of just an abstract class?
In the example posted, there appears to be no real reason to use an abstract class. In other scenarios, the abstract class could provide a common base to a subset of the interface implementations. With the interface providing a more stable/common abstraction for the rest of the application/library.
Generally I would only use an abstract class to share a common implementation, not as an interface definition - but that's just my preference. There are many different styles and patterns that people use.

Related

Why Use Interfaces Instead of Abstract Classes With DI?

I am beginning my journey of learning about dependency injection, and one of the reasons that I saw why it is a good idea to use DI was that it explicitly specifies your dependencies, which also makes your code more clear.
I have also noticed that interfaces are used abundantly, but I want to know why would we not use abstract classes for the sole purpose of specifying a default constructor?
Of course no implementation could be included in the abstract class.
Wouldn't this:
abstract class FooBase
{
protected IBar _bar;
FooBase(IBar bar)
{
_bar = bar;
}
abstract void DoSomething();
abstract void DoSomethingElse();
}
Demonstrate more clearly what the dependency of a FooBase object is more than:
interface IFoo
{
IBar Bar { get; }
void DoSomething();
void DoSomethingElse();
}
?
Please keep in mind I am new to this whole concept so be nice :)
One technical reason - forcing particular parent class in languages without multiple inheritance (Java/C#) will significantly restrict freedom of implementation of the "interface".
Note that there are 2 concepts hidden behind "interface" word and it sort of make it harder to reason in C#:
"interface" and abstract concept: well defined set of properties/methods to interact with an object; contract to work with an object.
"interface" as type in particular language (C#/Java) - one possible representation of
contract in given language.
Abstract/concrete classes can be used to represent contract, but force restrictions on implementers of contract in C#.
Some other languages (like C++) don't have such restriction and abstract classes is good option there. Other languages (i.e. "duck-types" JavaScript) does not have such class/interface distinction, but you can still have "contract" with an object.
Sample:
To provide more context where you should be hitting this restriction yourself in C#: DI is commonly used along with some form of TDD or at least with basic unit tests. So you try write some code and tests that uses abstract base class for DI.
abstract class Duck {
abstract void Quack();
}
class ConcreteDuck : Duck {...}
Now if you decide to write tests you may already have test classes that helps you to mock objects (if you are not using existing once)
class MockBase {...}
class MockDuck : MockBase,?????? // Can't use Duck and MockBase together...
Interface defines a contract. An Abstract base class defines a behavior.
Essentially, you can provide a single class that implements multiple interfaces,
which then in turn can be injected into multiple classes, but you will only have
a single abstract base class (at least in C#).
Consider the point of registering a type at the container (the composition root at best)
and consider the point where you resolve the dependency (the constructor or a property).
This SO will cover some more aspects SO on interface vs base class
In .NET, you only have single inheritance. In languages/frameworks where this is the case, opting to use an abstract class as your abstraction gives the potential to "burn the base class".
This means that you force the implementer of your abstraction to inherit from a singular class, when forcing them to do so might result in inconveniencing them severely, depending on what the implementation is.
Let's say that you have your abstract class Contract. If someone has their own Base class that they want to use which exposes only protected methods (for inheritors).
Because the methods are protected, one can't use encapsulation (an instance of Base stored in a field) to access the methods in Base for your abstraction implementation.
Even worse, if you don't have access to modify Base, then you might have to resort to some very ugly workarounds (Reflection, namely).
That said, with interfaces, you give the implementer the choice of where to inherit from and don't limit their options.
The typical pattern you'll see is that you always provide an interface for your contract and code your consumers against the interface. You also provide an abstract base class that provides functionality that people may derive from for convenience, but are not obligated to derive from.
Also, if it's possible for you to provide this functionality in the form of something that is easily encapsulated (for the condition I describe above), it would be even more optimal (you'd have an abstract class which just calls the instance that exposes the methods).

Are interfaces in C# inherited or Implemented

I have a simple question in C#
Are Interfaces inherited or are they implemented?
Thanks
Classes implement interfaces. Abstract classes are being inherited. A class can inherit from one class, but implement as many interfaces as you want it to.
However, interfaces can also "inherit" other interfaces. They don't really implement them, so it's more like inheriting their interface contracts, but they can implement multiple interfaces, so it's not really inheritance either. A class that will implement an interface which inherits from other interfaces, will have to implement all interface contracts that are included in the original interface, and it's base interfaces as well, recursively.
You should also read about abstract classes, for more useful information on the general subject.
That's just terminology. According to one MSDN page and another one a class or struct implements an interface. However, when you declare a new interface, that interface may inherit from other base interfaces.
that depends if the thing 'using' the interface is a class or another interface.
A class implements the interface (and any interfaces that it inherits).
Another interface inherits (or extends) an interface
You implement an interface by using a class. It is implemented, because it has no definition. Once you have a class. Be it abstract or a normal class, you inherit, because you are inheriting pre-built functionality.
Although there is 2 caveats.
abstract classes don't have to add any implementation to their methods (throwing exceptions is acceptable, or even leaving them empty, or marking the methods and properties as abstract to show the implementation is incomplete. Empty implementations are legitimate as long as the return type is satisfied. They just have to define the methods used by the interface.
you inherit from other classes, but adding 'sealed' to the class name will stop any one else from inheriting it e.g. System.String and System.Type
Classes can implement one / more interfaces implicitly and/or
explicitly.
An interface can inherit other interfaces.
The implicit implemented methods of an Interface can be abstract / virtual can be
overriden in derived classes.
In short Interfaces are implemented and implementation of the interfaces can be inherited

Can abstract classes have implementation in c#?

The compiler doesn't seem to mind it so far but I just wanted to double check whether I'm setting myself up for failure in any way by implementing certain methods in my abstract class.
An abstract class usually has one or more abstract method. So yes it can have some method implemented. The goal is to force the user to implement these methods to have an object working. Sometimes abstract classes are used to provide a 'base' implementation of some interfaces, leaving the final user to specify just the key methods. You can also have an abstract class without any abstract method: in this case you are asserting you must derive from that class in order to use it.
It's common to have some implementation in abstract classes.
If there is no implementation at all, consider using an interface instead of an abstract class.
Perfectly fine to implement some methods and leave others abstract.
If all methods had to be abstract, you might as well use an interface for it.
Yes. abstract class cannot be instantiated (you have to instantiate a class that inherits from your abstract class), but it can contains implementations.
it's fine and allowed, an abstract class has at least a member (method/property) not implemented so it cannot be instantiated.
an interface is also called pure abstract class which means it's 100% abstract, so does not allow you to specify any implementation.
keep in mind that there are lots of articles and opinions about never deriving a concrete class from another concrete class but only from abstract ones... at least this was the trend in C++ up to some years ago, then I moved to the C# side, started working more and had no time to keep reading those nice articles... :)

What is different between an abstract and an Interface class in C#?

What is different between an abstract and an Interface class in C#?
An interface is not a class, it is just a contract that defines the public members that a class must implement.
An abstract class is just a class from which you cannot create an instance. Normally you would use it to define a base class that defines some virtual methods for derived classes to implement.
Rather than writing whole thing here..
try http://www.codeproject.com/KB/cs/abstractsvsinterfaces.aspx
A class can implement multiple interfaces but can only inherit from one abstract class.
An abstract class can provide implementation for it's methods. An interface cannot provide implementations.
the level of interface is higher than abstract.
when u're design the strcuture, draw the uml, u should use interface.
when u're implement, then u should use abstract to extract repeat things.
anyway, the different is not only a syntax problem..
hope it helps.
Google "abstract class vs interface" and you'll get lots of explanatory articles...
A class can implement multiple
interfaces but can only inherit from
one abstract class.
Also, abstract classes may have some functions defined but interfaces will not have any function definition and the deriving class must define all of them.
I would explain this through the usage. Abstract class can be used when there is only one hierarchy, additionally without default implementation; while interface can be used across hierarchies (horizontally), often referred to as a behavior.
Interface is also an abstraction and in c# substitutes multiple class inheritance, so this may be confusing, but you have to distinguish when to use what.
Hope this helps,
Robert
The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.
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.

Abstract classes vs Interfaces

I'm a bit confused about the usage of Abstract classes in C#. In C++, it makes sense to define a template which classes inheriting the abstract class can follow. But, in C# doesn't Interface serve the same purpose?
True that abstract classes can have default implementation which is not provided by Interfaces. So if implementation doesn't need to be included in base class, is it better to go for Interfaces?
I still like to provide a default abstract implementation of an interface, assuming it's a substantial interface (and it makes sense). You never know when you might add something to the interface that has an easy default implementation that could be included and given "for free" to anyone who inherits from the abstract base class.
This CodeProject article has a lot of information on the difference between the two including a table comparing and contrasting the features of each.
Interfaces define the contract between classes - the ways classes call each other. A class can implement multiple interfaces, but can only inherit from one abstract class.
True that abstract classes can have default implementation which is not provided by Interfaces. So if implementation doesn't need to be included in base class, is it better to go for Interfaces?
Yes :). If it makes sense to implement some methods in the base class which will be common to all inhereted class you should use an abstract class. If the base class would only be used to define an interface but there is no common logic between the inherited classes, use an interface.
Interfaces and abstract classes serve different goals. Interfaces are used to declare contracts for classes while abstract classes are used to share a common implementation.
If you only use abstract classes, your classes cannot inherit from other classes because C# does not support multiple inheritance. If you only use interfaces, your classes cannot share common code.
public interface IFoo
{
void Bar();
}
public abstract class FooBase : IFoo
{
public abstract void Bar()
{
// Do some stuff usually required for IFoo.
}
}
Now we can use the interface and base implementation in various situations.
public class FooOne : FooBase
{
public override void Bar()
{
base.Bar(); // Use base implementation.
// Do specialized stuff.
}
}
public class FooTwo : FooBase
{
public override void Bar()
{
// Do other specialized stuff.
base.Bar(); // Use base implementation.
// Do more specialized stuff.
}
}
// This class cannot use the base implementation from FooBase because
// of inheriting from OtherClass but it can still implement IFoo.
public class FooThree : OtherClass, IFoo
{
public virtual void Bar()
{
// Do stuff.
}
}
For your first question, Yes.
For your second answer i'll give you some tips I've followed.
Use abstract classes and interfaces in combination to optimize your design trade-offs.
Use an abstract class
When creating a class library which will be widely distributed or reused—especially to clients, use an abstract class in preference to an interface; because, it simplifies versioning.
Use an abstract class to define a common base class for a family of types.
Use an abstract class to provide default behavior.
Subclass only a base class in a hierarchy to which the class logically belongs.
Use an interface
When creating a standalone project which can be changed at will, use an interface in preference to an abstract class; because, it offers more design flexibility.
Use interfaces to introduce polymorphic behavior without subclassing and to model multiple inheritance—allowing a specific type to support numerous behaviors.
Use an interface to design a polymorphic hierarchy for value types.
Use an interface when an immutable contract is really intended.
A well-designed interface defines a very specific range of functionality. Split up interfaces that contain unrelated functionality.
You can implement any number of Interfaces, but can only inherit one Class. So Classes and Interfaces are quite different beasts in C# and you cannot use them interchangeably. In C# abstract classes are still classes, not interfaces.
If you don't have any default/common code, then go with an interface.
An abstract class can also serve as a template, where it defines the steps of some algorithm and the order in which they are called, and derived classes provide the implementation of these steps:
public abstract class Processor
{
// this is the only public method
// implements the order of the separate steps
public void Process()
{
Step1();
Step2();
//...
}
// implementation is provided by derived classes
protected abstract void Step1();
protected abstract void Step2();
}
Whilst it's true that an abstract class with no implementation is equivalent to an interface, interfaces and abstract classes are used for different things.
Interfaces can be used for polymorphism in the most general sense. For example, ICollection is used to define the interface for all collections (there are quite a few). Here it is defining the operations that you want to perform on a certain kind of type. There are many other uses (such as testability, dependency injection etc). Also, interfaces can be mixed and this works both conceptually and technically.
Abstract classes are more to do with templateable behaviour, where virtual methods are a place to 'fill in the gaps'. Obviously you can't mix abstract classes (at least, not in C#).
In C# a large deterrent for the use of abstract classes is that you can only use one. With interfaces you have the advantage of not limiting the base class for the implementation. To this end, I always use an interface even if I create an abstract base class to aid with the implementation.
Often another annoyance of base abstract classes is that they tend to rely on template arguments. This can make it very difficult for the rest of your code to utilize. The easy answer for this is to provide an interface to talk to the abstract class without knowing the type argument of the template class.
Others seem to be typing their answer faster, but allow me to summarize...
Use an interface. If you need to share implementation, you can also create an abstract base class that provides common implementation details.
Note that with C#3, you can provide default behavior for interfaces through the use of extension methods. There are some limitations, though, and abstract classes still have their place.
The rule I follow when modeling is:
Classes(abstract included) and structs model entities.Interfaces model behavior.
Entities implementing an interface can be considered as exhibiting behaviors that the interface(contract) exposes.
This is hinted at in a few of the answers but not explicitly stated.
The fact that you can implement multiple interfaces and only inherit from one base class, as if they were two sides of the same coin, isn't a good way to look at it.
Don't think of interfaces as part of an object hierarchy. They are usually just small parts of functionality (or at least specific if not small) that your real object heirarchy can declare as implementing. Take IDisposable for instance. If you were the one writing that, would you ask yourself whether it should have been an abstract class or an interface? It seems obvious that in this case they are two completely different things. I want to BE disposable. Think ICloneable and IEnumerable. You can implement those in your class without having to try and make your class derive from some unrelated classes like List or Array. Or take IEnumerator. Simply gives a MoveNext type of view to an object. My class can provide that functionality without having to awkwardly be derived from some other sequential collection data type that has nothing to do with my class.
I always prefer interfaces as long as the base class don't have some really "heavy duty" implementation that will save lots of time to the implementers.
giving that .net allows only one base class inheritance, forcing your users to inherit is a huge limitation.
You should always prefer programming to interfaces than to concrete classes.
If you also want to have a default implementation you can still create a base class which implements your interface(s).

Categories