Abstract class or interface. Which way is correct? - c#

There are two way for choosing between abstract class or interface. Microsoft solution and Oracle solution:
Microsoft, design guideline:
Do use abstract (MustInherit in Visual Basic) classes instead of interfaces to decouple the contract from implementations.
http://msdn.microsoft.com/en-us/library/ms229013.aspx
Oracle, The Java Tutorials:
If an abstract class contains only abstract method declarations, it should be declared as an interface instead.
http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
My question is which way is correct? Microsoft or Oracle solution? Note that I think choose between abstract class or interface should not depends on programming language (Java or C#).

If I recall my blog reading correctly, the Microsoft advice to use abstract classes stems from the ability to reuse implementation with an abstract class, something you can't do with an interface.
Note also that the Microsoft page you linked to is specifically guidance for writing code libraries for sharing/reuse across multiple projects. The likelihood in this situation is that you'll be writing all the implementations of the interface yourself, probably within the same assembly. Good practices for working on a single product or system will vary somewhat.
One common approach that I've seen across a number of codebases in a number of languages is this:
Define an interface to specify the contract
Create an abstract class implementing the contract to provide any common implementation useful to all descendants
Implementations of the contract then have the option to start from the base class for convenience, or just to implement the interface if they want full control
A fourth step common in the .NET world is to provide convenience extension functions built on the interface.

They are 2 statements for different contexts.
The Microsoft guideline you quote from is for "Designing Class Libraries". And it states the reason for favoring abstract classes there: you can add functionality without breaking anything.
For separation and decoupling over layers and other boundaries, Microsoft also advices interfaces.

An interface carries no implementation - it's a contract. It allows for complete decoupling.
I will go from an interface to an abstract (base) class if I want to provide some common implementation while forcing on the inheriting class concrete class to provide some implementation specific to that class. That's provides a little less decoupling.
Also be aware that many languages like C# (and .net languages like VB.net etc...) as well as Java do not allow multiple inheritance so interfaces become a way of allowing a class to have many behaviors.

Related

what is the main utility of Interface in real world programming [duplicate]

This question already has answers here:
Interface vs Base class
(38 answers)
Closed 9 years ago.
what is the main utility of Interface. we know that we can implement dynamic behaviour using interface but i guess it is not only the utility. so i like to know when we have to write interface and when we need to go for abstract class.
show me 5 or 10 most important uses of interface in real life scenario.
another main use is coming to my mind that project manager or team lead will implement basic skeleton through interface and other developer follow it.
so please guys show me with sample code few most important use of interface which we can do with abstract class or concrete class.
one guy told me like this way which is not very clear to me
interfaces are defined contracts between classes or structs, consumers can exchange the implementation by a different one as long as the same contract is met that is the method names and signature that compose a specification that classes and structs can work against rather than working against a concrete implementation.
The important part about interfaces is to know when to use them and as a matter of fact it's quite simple, when you want two or more unrelated objects to have the same common functionality but not necessarily the same implementation you will want to use interfaces; otherwise, when you have related objects that have a shared functionality and implementation then you may consider to use an abstract class instead of an interface.
this thing is not clear specially
when you want two or more unrelated objects to have the same common functionality but not necessarily the same implementation you will want to use interfaces; otherwise, when you have related objects that have a shared functionality and implementation then you may consider to use an abstract class instead of an interface.
it would be nice if anyone explains with sample code when to go for interface & when abstract class.
show me few best important area which is always handle with interface with sample code or best interface uses with sample code.thanks
Some of microsoft recommendation from this link
If you anticipate creating multiple versions of your component,
create an abstract class. Abstract classes provide a simple and easy
way to version your components. By updating the base class, all
inheriting classes are automatically updated with the change.
Interfaces, on the other hand, cannot be changed once created. If a
new version of an interface is required, you must create a whole new
interface.
If the functionality you are creating will be useful across a wide
range of disparate objects, use an interface. Abstract classes
should be used primarily for objects that are closely related,
whereas interfaces are best suited for providing common
functionality to unrelated classes.
If you are designing small, concise bits of functionality, use
interfaces. If you are designing large functional units, use an
abstract class.
If you want to provide common, implemented functionality among all
implementations of your component, use an abstract class. Abstract
classes allow you to partially implement your class, whereas
interfaces contain no implementation for any members.
I won't answer all you questions. I just want to give you some hints.
The main difference between an interface and an abstract class is, that a c# class can implement multiple interfaces even if they declare the same members. And it can even implement those equally named members differently by implementing the interface explicitly.
If you derive from an abstract class, you also "inherit" al its dependencies. For example if a method in an abstract class uses another class from a different assembly, you have to reference that assembly. --> Compile order --> No parallel build
Mocking in unittest can be trickier when using abstract classes with base functionality
Let's take for instance some Data Access Objects which can retrieve data from a DB, a SAOP Service, a REST Service or even an XML file.
You would use Interfaces to ensure what kind of operations they offer to the rest of the application. You can also say that those interfaces describe the Domain and how they interact with it.
public interface IUserDao
{
User GetUserById(int id);
void AddUser(User u);
....
}
This IUserDao can be implemented by using WCF, Entity Framework, XmlDocuments, and many other techniques, the controller or other parts of the application don't care about the details as long as they have those abstracted methods to retrieve and add a user.
On the other hand the same Data Access Objects can have a base class which can for instance initialize some connections or open the XmlDocument, ...
public abstract BaseDao
{
public Connection GetNewConnection()
{
....
}
// or similar functions which are used by DAOs accessing the same data source (DB, XML, ...)
}
So as it was described, you can use interfaces to hide implementation details and bring the implementation to a more absract level, this way, less skilled developers or developers more interested in the domain specific aspects (some specific calculation, ...) can contribute without the need to understand how exactly they need to retrieve and store the data from / to the database.
Also it is easier to exchange functionality, for instance you can start with a simple xml file but soon you'll realize that you'll need a whole DB - you can keep the interfaces and implement the classes with DB access.
On the other hand abstract classes share basic functionality (technical functionality), which is so basic that it is used by many classes but shouldn't be instantiated alone. You could exchange Abstract Classes for some utility classes with static methods, but than you would loose the advantages of OOP.

Plugin pattern in C#

Problem:
I am constructing a framework which accepts a file, translates it and executes it. The framework should be able to handle any type of file, to this end i have provided a method of uploading a DLL containing classes and methods for translating and executing a file. What i am looking for, is the best way to define the plugin interface
Solution A:
Define a set of interfaces which are publicly available. Plugins should implement these interfaces.
Solution B:
Define some abstract classes which are publicly available. Plugins should inherrit and override the abstract methods on these classes.
Solution C: rcravens
Pass interfaces around inside the code, create an abstract class which is publicly available to allow for plugin extensibility. Chosen
This solution was chosen ahead of interface only because it enables basic implementation (handy in this case). It was chosen ahead of abstract class only because it enables mocking within the code. The composition frameworks are excellent, but a bit over the top for something as lightweight as this application where only limited extensibility is desired.
Solution D: Jay and Chris Shain
Implement a composition framework (such as Managed Extensibility Framework(MEF)) and build around it
If any new solutions appear, i will add them to this list. The answer will go to the person who is best able to justify their solution (possibly with advantages and limitation)
Thanks in advance,
Tech Test Dude
What you are writing sounds suspiciously like what Managed Extensibility Framework supports: http://mef.codeplex.com/. Maybe just use that and avoid re-inventing the wheel?
At the lowest level I believe you need interfaces. This allows most mocking frameworks to easily provide fakes. Around your code you should pass around the interfaces. If you need some base implementation that can be refactored into an abstract base class, then do it. Abstract base classes and interfaces are not mutually exclusive concepts. Some times it makes sense to have both.
I don't think there's a better solution between interface or abstract class, it really depends on what you need. But personnally I would probably go with abstract class, for the simple fact that it offers more flexibility.
You could provide some abstract methods that are essential to define particular behavior of the plugin, while virtual methods offers a way to optionnaly override a default behavior.
The abstract class also can provide some utility methods that could be usefull to the plugin's authors.
Basically, an abstract class can offer all that an interface offer, and more. So it's probably a better for future extension.

Inheritance vs. interface in C# [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Interface vs Base class
When should I choose inheritance over an interface when designing C# class libraries?
So I'm writing my first real program in C#. The program will scrape data from four different websites. My plan is to have one parent class that will look like this:
class Scraper
{
string scrapeDate(url);
string scrapeTime(url);
//&c.
}
Then I will have four classes that inherit from it.
The other option is to make Scraper an interface and have four classes implementing it.
What are the differences between these approaches?
Class inheritance represents an "is-a" relationship, e.g., a Tank is a Vehicle. If your situation doesn't at least meet this, choose interface over inheritance.
If the proposed base class doesn't provide default implementations for your methods, this would be another reason to choose interface over inheritance.
In C#, you can only inherit from one class but multiple interfaces. This would be yet another reason to choose interface over inheritance.
Get the idea?
Inheritance is, in my opinion, the better approach when it is possible. Implementing common features in a base class helps ensure that the underlying implementation is consistent, while implementing an interface guarantees only that the, well, interface is consistent. Inheritance wherever possible is one leg of the OOP tripod, and limits code duplication.
I use interfaces when I have objects that can't or shouldn't have a common base class, but need to be provide similar functionality. Classes that implement a common interface may (and probably do) expose additional functionality, may implement multiple interfaces, etc.
For instance: in one application, my data access layer is built around "provider" classes, which insulate business objects and database proxy objects from the database. In one instance, I have a provider which interacts with a SQL Server database and another for communicating with Oracle CRM On Demand (aka, Why God Why). The both implement an agnostic interface so that the client code doesn't care which data store it's dealing with, or the quirks of working with each.
The Oracle provider communicates with a hosted server via a collection of web services, manages connection sessions, batches requests, etc. The SQL provider uses a set of stored procedures. Although both interfaces accept the same data classes, the Oracle provider transforms the data to match their esoteric (to put it lightly) schema. With this implementation, I could easily add a provider to use an XML data store, a different RDBMS, or a stub/mock unit test.
In this situation, it doesn't make much sense for these things to have a common base class and, in a few instances, it's impossible.
Honestly, do both.
public interface IScraper
{
string ScrapeDate(string url);
}
public abstract class Scraper : IScraper
{
public string ScrapeDate(string url)
{
// default implementation
}
}
There's advantages either way, but those are difficult to quantify without knowing more about your requirements. However, there's no reason you can't do both. Having an interface for your class makes it mockable for testing purposes as well.
Something else to consider though; if the functionality for each of your derived classes are similar enough, it may be easier to simply have a single class that takes parameters to the constructor.
An interface contains only the signatures of methods, delegates or events. The implementation of the methods is done in the class that implements the interface.
A class can implement multiple interfaces.
A class can have only one direct base class.
Refering to Abstract Class versus Interface.
There are some similarities and
differences between an interface and
an abstract class:
A class may implement several
interfaces.
A class may inherit only one abstract
class.
An interface cannot provide any code,
just the signature.
An abstract class can provide
complete, default code and/or just the
details that have to be overridden.
An interface cannot have access
modifiers for the subs, functions,
properties etc everything is assumed
as public
An abstract class can contain access
modifiers for the subs, functions,
properties
Interfaces are used to define the
peripheral abilities of a class. In
other words both Human and Vehicle can
inherit from a IMovable interface.
An abstract class defines the core
identity of a class and there it is
used for objects of the same type.
If various implementations only share
method signatures then it is better to
use Interfaces.
If various
implementations are of the same kind
and use common behaviour or status
then abstract class is better to use.
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.
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.
No fields can be defined in interfaces
An abstract class can have fields and
constrants defined
Interfaces allows to define the structure of common behaviors.
Inheritance is useful if you can extract a common implementation of one or more specific behaviors.
Basically if several classes scrape a date the same way, it make sense to put scrapeDate in a base class; otherwise use only an interface and define the specific scrapeDate in every class that implement your interface.
If you have common functionality, you should use inheritance - the functionality will then be available in all child classes, and each child class can extend or override the parent class code.
If you have something consuming your classes, you would use interfaces to ensure that all of the classes implement the same methods and properties, but not necessarily the same functionality.
Main differences:
an interface has no implementation at all, whereas an abstract base class can implement common functionality
a class can only inherit from one base class, but it can implement multiple interfaces
In your case, it's likely that all your scraper classes will need some common features, so it makes sense to make them all inherit from a common base class
What you appear to have here is really best served as an Interface. If you were to have some common logic you wished to include or some common data members you wished to include then you would use a Base Class and inherit from it. What you are doing is requiring each child to implement a minimum set of logic.

Multiple inheritance is not supported in dotnet. But multiple interface supports? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Multiple Inheritance in C#
Multiple inheritance is not supported in dotnet. But multiple interface supports. Why this kind of behaviour exists.
Any specific reasons??
You can simulate multiple inheritance using interfaces. If multiple inheritance with classes were allowed, it would lead to the Diamond problem.For reasons multiple inheritance is not supported, I suggest you read Why doesn't C# support multiple inheritance?
Different languages actually have
different expectations for how MI
works. For example, how conflicts are
resolved and whether duplicate bases
are merged or redundant. Before we can
implement MI in the CLR, we have to do
a survey of all the languages, figure
out the common concepts, and decide
how to express them in a
language-neutral manner. We would also
have to decide whether MI belongs in
the CLS and what this would mean for
languages that don't want this concept
(presumably VB.NET, for example). Of
course, that's the business we are in
as a common language runtime, but we
haven't got around to doing it for MI
yet.
The number of places where MI is truly
appropriate is actually quite small.
In many cases, multiple interface
inheritance can get the job done
instead. In other cases, you may be
able to use encapsulation and
delegation. If we were to add a
slightly different construct, like
mixins, would that actually be more
powerful?
Multiple implementation inheritance
injects a lot of complexity into the
implementation. This complexity
impacts casting, layout, dispatch,
field access, serialization, identity
comparisons, verifiability,
reflection, generics, and probably
lots of other places.
yes inheritance means getting the properties from one class object to another class object..
here in interface concept we are not at all getting any properties rather we are implementing the unimplemented methods of interface in class...
so inheritance and intefaces are quite opposite...
so finally java supports only syntax of multiple inheritance does not supports implementation of multiple inheritance....
inheritance is like debit and interface is like credit....but interface has its own importance in other concepts like server side programming...
In general, multiple inheritance creates more problems than it solves. Think about how virtual method calls have to be resolved. What if a class doesn't define a method but both of its parents do? Which one should execute?
Implementing multiple interfaces, however, has no such problems. If two interfaces define the same method and you actually try to implement them, your code won't even compile (although I'm unsure if you could explicitly implement them and satisfy the compiler requirements).
Because interfaces do not the
implementation details, they only know
what operations an object can do.
Multiple inheritance is difficult when
there are two different
implementations are found for the
method with same signature in both the
base classes. But in case of interface
both the interface may define a common
method with same signature but they
are not implemented at the interface
level, they are only implemented by
the object or type that implement both
the interfaces. Here though there are
two different interfaces defining two
methods with same signatures, the
object provides the common
implementation satisfying both the
methods in both the interfaces. So
there is no ambiguity between
implementations, both the methods have
common implementation hence you could
have multiple inheritance in case of
interfaces.
The danger with multiple inheritance of concrete classes is that there is storage and virtual method lookup that must be reconciled between the two or more parents of a given class. Especially tricky is when there are shared ancestors. But interfaces only define what a class should look like, not how it needs to be implemented and it's much easier to make a class look like a lot of different things than it is to make it be a lot of different things. Two interfaces can require a method int Foo() and an implementing class can safely use both interfaces and implement Foo() without causing headaches for which base Foo() to override, etc.
Another reason is that constructor chaining is difficult to manage with multiple inheritance. But interfaces don't specify constructors, so that problem is entirely sidestepped.
There are certainly many other reasons why multiple inheritance is bad.
java supports syntactical multiple inheritance....java does not supports implementation of multiple inheritance...
some people says java supports multiple inheritance through interfaces ...but its not correct here the explanation:
inheritance ::
getting the properties from one class object to another class object..
Class A{}
Class B extends A {}
here object of class A getting the properties(methods/functions/ & data members/class variables)
why java does not supports multiple inheritance using classes:
Class A{} Class B{} Class C extends A,B{} X--this statement causes error because Class A getting object of object class from both sides A and B...
every java class by default extending Object of object class...and Object of object class is the root object means super class for all classes...
but here Class c having two super classes of object...so giving error...means java does not support multiple inheritance by using classes..
is java supports multiple inheritance using Interfaces::
because of this interface concept only few of us saying that java supports multiple inheritance....but its wrong..
here the explanation::
interface A{}
interface B{}
interface C implements A , B{}
(or) interface A{}
interface B{}
Class C implements A , B{}
here its look like multiple inheritance but .....
inheritance means getting the properties from one class object to another class object..
here in interface concept we are not at all getting any properties rather we are implementing the unimplemented methods of interface in class...
so inheritance and intefaces are quite opposite...
so finally java supports only syntax of multiple inheritance does not supports implementation of multiple inheritance....
inheritance is like debit and interface is like credit....but interface has its own importance in other concepts like server side programming...

Benefits of implementing an interface

what are the benefits of implementing an interface in C# 3.5 ?
You'll be able to pass your object to a method (or satisfy a type constraint) that expects the interface as an argument. C# does not support "duck typing." Just by writing the methods defined by the interface, the object will not automatically be "compatible" with the interface type:
public void PrintCollection<T>(IEnumerable<T> collection) {
foreach (var x in collection)
Console.WriteLine(x);
}
If List<T> did not implement the IEnumerable<T> interface, you wouldn't be able to pass it as an argument to PrintCollection method (even if it had a GetEnumerator method).
Basically, an interface declares a contract. Implementing an interface enforces your class to be bound to the contract (by providing the appropriate members). Consequently, everything that relies on that contract (a method that relies on the functionality specified by the interface to be provided by your object) can work with your object too.
The main benefit is about code readability, code maintainability and code "semantics".
Code readability: An interface constitutes a declaration about intentions. It defines a capability of your class, what your class is capable of doing. If you implement ISortable you're clearly stating that your class can be sorted, same for IRenderable or IConvertible.
Code semantics: By providing interfaces and implementing them you're actively separating concepts in a similar way HTML and CSS does. A class is a concrete implementation of an "object class" some way of representing the reality by modeling general properties of real life objects or concepts. An interface define a behavioral model, a definition of what an object can do. Separating those concepts keeps the semantics of your code more clear. That way some methods may need an instance of an animal class while other may accept whatever object you throw at them as long as it supports "walking".
Code maintainability: Interfaces helps to reduce coupling and therefore allow you to easily interchange implementations for the same concept without the underlying code being affected. You can change the implementation of a IMessage easily by defining a new class that implements the interface. Compare that to sistematically replacing all references from CMessage to CMyNewMessageClass.
It will help when you try to:
Unit test with Stubs / Mocks
Implement Dependency injection
Solve world hunger (although this unproven!)
Kindness,
Dan
Interfaces provide no actual advantage. Anything that can be done with an interface can, and should be done using other language constructions. Multiple inheritance is oft quoted as the only REAL benefit derived from using interfaces, but I can do multiple inheritance quite easily and clearly in C# - I do it every day. Changing the code without "breaking" the interface is the silliest of all excuses... That applies the same to concrete classes as it does to abstract classes or interfaces. As long as the functional signature does not change, you haven't broken the interface. Doesn't matter where it was declared. Simply putting a functional prototype in a separate file and naming it with an "I" in front buys nothing - except that you end up with twice as many source files to maintain. The supposition that the interface is defined early, and then maintains the contract is ridiculous. Interface methods and their parameters change ALL the time, because everything is never known up-front. That's why MicroSof stopped using them long ago. They had IUnKnown, IUnknown2, etc. It created a mess.
The main benefits of interfaces is mostly related to project design.
If you use an interface:
The consumer of the interface should implement that interface.
Designing bridge patters.
Creating a contract so that user must adhere the rules of the interface.
Can take only interface part (Object) from the main class.
Even class is private, can obtain the interface object from that
Multiple inheritance kind of style.
Need not be should implement, simple go for if implements that means if you want you can implement other wise can drop it..
Cleaner code.
Implementation which changes depends on class can go ahead with interface.
If each class have separate implementation of a method better to go for interfaces. For example IEnumerable in collections.
According to C# Architect, in a simple word it's a contract. Consumer must adhere to it.
An interface defines a contract (things that an object is able to do), while a concrete class (or struct) defines the concrete behavior.
For an example, IList is an interface, it defines the methods that a concrete object has to provide in order to be used like any other object implementing IList. Everywhere an IList can be used, your object that implements IList can be used as well. The way you concretely implement it and the way your object behaves when those IList methods are called is left to you.
If you work in a huge, commercial software house - you MIGHT want to consider the judicial use of Interfaces. Otherwise, you should stay away from them. Same for multi-threading. If I see one more script-kiddie app that spawns 20 threads to write "Hello World" I'm gonna freak. Multi-threading should be completely reserved for apps that require it, usually in a multi-processing environment. 90% of the time it causes more harm than good. And don't bother with the thread highjack / off-topic comments. I don't care. I've been doing this longer than most of you have been alive. Rank has its privileges.
You aren't tied to class inheritance - you can apply an interface to any class. Any class can have multiple interfaces - C# doesn't support multiple class inheritance, i.e. you are providing a good abstraction layer through the interface
An Interface is a reference type and it contains only abstract members. Interface's members can be Events, Methods, Properties and Indexers. But the interface contains only declaration for its members. Any implementation must be placed in class that realizes them. The interface can't contain constants, data fields, constructors, destructors and static members. All the member declarations inside interface are implicitly public.
The way I understand it interfaces are most useful in these cases:
Cleaner division of labor among programmers. Lead programmer writes interface and junior programmer writes its implementation. That makes perfect sense to me. Lead programmer could write pseudocode instead of interface though.
Some specific situation, where you need 2 or more different implementations of the same class, for example interface animal and classes tiger and lion that use it. And even here it doesn't makes much sense, because lions and tigers share some things in common. Abstract class would be better, because if you use interface you have to write common functions in separate classes which leads to code duplication, which is bad.
You write a library and want it to be modifiable by users. So you write interface and its class implementation. User of your lib still has the possibility to write his own implementation class, which may use different technology/algorithm which achieves the same result, but maybe in a faster way for example. This is also the reason why we meet so many interfaces in libs we use, but rarely feel the need to write our own interfaces. Because we don't write libraries.

Categories

Resources