Inheritance vs. interface in C# [duplicate] - c#

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.

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.

What is the philosophy behind the creation of the Interface infrastructure in OOP?

I believe we invent things for some reasons: OOP came because procedural programming didn't meet our needs; The same goes for the Interface, because other OOP features like Abstract didn't meet our needs.
There are plenty of articles and guides written about what an Interface IS, CAN DO and HOW TO USE IT, however, I'm wondering what the actual philosophy behind the of creation of Interface is? Why we need to have Interface?
Conceptually, an interface is a contract. It's a way of saying that anything implementing this interface is capable of doing these set of things.
Different languages have different things that interfaces can define, and different ways of defining them, but that concept remains.
Using interfaces allows you to not care how some particular task is completed; it allows you to just ensure that it is completed.
By allowing implementations to differ, and allowing the code to define just the smallest subset of what it needs, it allows you to generalize your code.
Perhaps you want to write a method to write a sequence of numbers on the screen. You don't want to go around writing methods for doing that for an array, a set, a tree, on any of the (many) other commonly used data structures. You don't need to care whether you're dealing with an array or a linked list, you just need some way of getting a sequence of items. Interfaces allow you to define just the minimal set of what you need, lets say a getNextItem method, and then if all of those data structures implement that method and interface they can use the one generalized method. That's much easier than writing a separate method for each type of data structure you want to use. (This isn't the only use of interface, just a common one.)
In Java, classes can inherit just from one class, but they can implement multiple interfaces. Interfaces are similar to abstract classes, but if a class extends an abstract class then that class can't extend any other class. Interfaces solve that problem, you can make a class extend an abstract class and implement many interfaces.
I completely agree with susomena, but that's not the only benefit you get, when using interfaces.
For example. In our current application, mocking plays an important role, regarding unit testing. The philosophy of unit testing is, that you should really just test the code of this unit itself. Sometimes, though, there are other dependencies, the "unit under test" (SUT) needs to get. And maybe this dependency has other dependencies and so forth. So instead of complicatetly building and configuring the dependency tree, you just fake this certain dependency. A lot of mocking frameworks need to be setup with the interface of the class, which the SUT depends on. It is usually possible to mock concrete classes, but in our case mocking of concrete classes caused weird behaviours of unit tests, because of constructor calls. But mocking interfaces didn't, because an interface hasn't got a constructor.
My personal philosophy of choosing an abstract class implementation is building an hierarchical class construct, where some default behaviour of the abstract base class is needed. If there isn't any default behaviour, the derived class should inherit, I don't see any points of not choosing an interface over an abstract class implementation.
And here an other (not too good) example of how to choose one over another technique. Imagine you got a lot of animal classes like Cat and Dog. The abstract class Animal might implement this default method:
public abstract void Feed()
{
Console.WriteLine("Feeding with meat");
}
That's alright, if you got a lot of animals, which just are fine with meat. For the little amount of animals, which don't like meat you'd just need to reimplement a new behaviour of Feed().
But what if the animals are a kinda gourmets? And the requirement was, that every animal gets its preferred food? I'd rather choose an interface there, so the programmer is forced to implement a Feed() method for every single type of IAnimal.
IMO the best text that describes interface is the ISP from Robert Martin.
The real power of interfaces comes from the fact that (1) you can treat an object as if it has many different types (because a class can implement different interfaces) and (2) treat objects from different hierarchy trees as if they have the same type (because not related classes can implement the same interface).
If you have a method with a parameter of some interface type (eg., a Comparable), it means this methods can accept any object that implements that interface "ignoring" the class (eg., a String or a Integer, two unrelated classes that implement Comparable).
So, an interface is a much more powerful abstraction than abstract class.
Interfaces were brought into OOP because of the sole reason of it's use in the producer consumer paradigm. Let me explain this with an example...
Suppose there is a vendor that supplies tyres to all the big shot automobile companies. The automobile comapny is considered to be the CONSUMER and the tyre vendor is the PRODUCER. Now te consumer instructs the producer of the various specifications in which a tyre has to be produced(such as the diameter, the wheel base etc.); And the producer must strictly adhere to all of these specs.
Let's have an analogy to OOP from this... Let us develop an application to implement a stack, for which you are developing the UI; and let us assume that you are using a stack library (as a .dll or a .class) to actually implement the stack. Here, you are the consumer and the person who actually wrote the stack program is the producer. Now, you specify the various specifications of the stack saying that it should have a provision to push elements and to pop elements and also a provision to peep at the current stack pointer. And you also specify the interface to access these provisions by specifying the return types and the parameters (prototype of functions) so that you know how to use them in your application.
The simplest way to achive this is by creating an interface and asking the producer to implement this interface. So that, no matter what logic the producer uses(u are not bothered about the implementation as long as your needs are met one way or the other), he will implement a push,pop and a peep method with exact return types and parameters .
In other words, you make the producer strictly adhere to your specs and the way to access your needs by making him implement your interface. You won't accept a stack by just any vendor, if he doesn't implement your interface; Because you cannot be sure if it'll suit your exact need.
class CStack implements StackInterface
{//this class produced by the producer must have all three method implementation
//interface defined by the consumer as per his needs
bool push(int a){
...
}
int pop(){
....
}
int peep(){
...
}
}

Class hierarchy design - interfaces + base class vs. abstract class

Sometimes I wonder that we do have interfaces and abstract classes for two different reasons:
If you just want multiple implementations for design purposes and something to code against at the development time then interface is the best choice that we have got.
If you want to reuse the code then we might go for the abstract classes.
BUT, I have seen something that is neither.
In some designs, it is like this Interface > BaseClass > Child class.
So basically a base class implements all the methods and then the child class inherits the definition from it. Why can we not use an abstract class instead of this setup? Or this is a flawed setup?
The most simple reasining is if an object has a IS-A relation then use an (abstract) base class. Like a horse IS an animal.
If there is a CAN relation, then think about interfaces, like if a Duck CAN fly, use IFlying as interface for a duck that can fly.
Interfaces can be used to implement multiple interfaces into one class. You can't derive from multiple classes in C#.
This answers posted on this site about Abstract classes and interfaces will help you understand the design differences.
It's a matter of design and personal taste, usually when you declare a interface you don't really care about the specific implementation but you just care about the wrapped functionality that the interface should provide.
Having an abstract class does define some specified behavior, this is something that you don't want always.
At the same time having abstract classes would forbid you from inheriting more than one, so this would limit the functionality it can have.
When designing a class hierarchy you question yourself "what should object used in this situation be able to do?" and define an interface for that functionality, then, while providing implementation, you can realize that some of that functionality should be grouped and reused for some child classes but it is something that comes later.
It is due to multiple inheritance of classes is prohibited in C#. But it is allowed to implement multiple interfaces.
An interface is essentially a contract of a piece of functionality; specifying certain methods and properties. Sections of code can be written against this interface without any knowledge of the implementation detail.
An abstract class may implement some interface(s), but it may also contain some common functionality that all derived types may need. It may also include abstract or virtual methods/properties that allow derived types to customize some of the functionality.
Consider a scenario where you construct some object model, that you code against, using interfaces to define the structure of said model, but you want to allow consumers of that code to potentially write their own implementations if they so wish, without affecting the core design. You may then build your own implementation with some base class for one implementation. Derived types would then inherit this base class, which in turn implements the interfaces of your object model. Someone else may then come along and write their own implementation, but want some different functionality or behaviour to your existing implementation. As such, they write their own base class with their common functionality, and extend it with their own derived types.
Following this scenario, there is no real reason why the use of both an abstract class and and interface should not be used. It all depends on your purpose and how you are constructing your code.
An interface defines a set of attributes and functionality that a class must implement and can be implimented by any number of classes. There is no reason why a base class should not implement an interface. For example many different base classes might use IComparable.
Main rules for an interface are
All methods should be abstract
No implementation
Interface can extend any number of Interfaces
All fields should be public, static and final
All methods should be overridden in the inherited class

Abstract class or interface. Which way is correct?

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.

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...

Categories

Resources