33

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?

Community
  • 1
  • 1
Hui
  • 13,887
  • 8
  • 25
  • 20
  • 1
    Most likely a duplicate, and a question without any effort. – Steven Jeuris May 31 '11 at 14:12
  • 10
    This is a valid question for a beginner, downvoting was not called for. Take an upvote from me. – Bueller May 31 '11 at 14:15
  • 1
    @Bueller: Since when are duplicate questions promoted? – Steven Jeuris May 31 '11 at 14:15
  • 4
    @Steven: At least [since November of 2010](http://blog.stackoverflow.com/2010/11/dr-strangedupe-or-how-i-learned-to-stop-worrying-and-love-duplication/). – Cody Gray - on strike May 31 '11 at 14:40
  • @Cody Gray: That's not promoting duplicate questions, that is allowing them, and marking them as such. If you can't find your answer immediately, I agree, duplication is useful. But 'promoting' a question by upvoting it while the answer already popped up in _"Questions with similar titles"_? ... or just a simple google search. – Steven Jeuris May 31 '11 at 14:50
  • 5
    @Steven: I mean, I agree with you to some extent. I vote to close a *lot* of questions as duplicates, because I think it's best to consolidate the answers and information all in one place. But you've made several comments here that appear to denigrate the user for even *asking* a duplicate question, which I felt like misses the point. The reason we have the ability to vote to close a question as a duplicate is because it's a gut call. If you're really a beginner, you might know about "inheritance" and "interfaces", but not about "base classes". Terminology is hard. You might miss the dupe. – Cody Gray - on strike May 31 '11 at 23:17
  • @Cody: Fair enough. Usually I'm more friendly about it, but this just seemed so straightforward to me. The problem is there are a lot more people who can ask 'easy' questions than there are to answer difficult ones/moderate them. I flagged this yesterday and it still didn't get any attention (flag weight 200). But actually, no reason to continue discussing here. [This meta post](http://meta.stackexchange.com/q/50358/157047) kinda says it all. – Steven Jeuris Jun 01 '11 at 08:06
  • 1
    I up-vote, valid beginner question. – abraham camhy Nov 27 '16 at 22:54

9 Answers9

58

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?

Matt Davis
  • 45,297
  • 16
  • 93
  • 124
13

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.

3Dave
  • 28,657
  • 18
  • 88
  • 151
8

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.

Flynn1179
  • 11,925
  • 6
  • 38
  • 74
5

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

Akram Shahda
  • 14,655
  • 4
  • 45
  • 65
4

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.

ipavlic
  • 4,906
  • 10
  • 40
  • 77
2

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.

Johann Blais
  • 9,389
  • 6
  • 45
  • 65
1

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.

Duncan Howe
  • 2,965
  • 19
  • 18
1

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

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
1

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.

Bueller
  • 2,336
  • 17
  • 11