Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method return an interface

Hi All,

I'm thinking in this line of code

IDataReader myReader = questDatabase.ExecuteReader(getQuest);

I'm using DAAB but I can't understand how and what's the meaning of the fact the method ExecuteReader(DbCommand) returns an IDataReader Interface.

Anyone can Explain, Please

like image 408
netseng Avatar asked Feb 04 '09 13:02

netseng


People also ask

Can methods return an interface?

Since an interface provides all of that, you can call methods on it, just as you can on a regular class. Of course, in order for the method to actually return some object, there needs to be some class that implements that interface somewhere.

Can a method return an interface C#?

Yes, you can return an interface.

Can interface methods have return type in Java?

Note: You also can use interface names as return types. In this case, the object returned must implement the specified interface.


1 Answers

It allows you to you DataReader without the need of knowing which type of DataReader you are using (i.e. SqlDataReader, OleDbDataReader, EtcDataReader), so if someday you want to change the datareader you are using it won't impact you logic, in other words it gives you abstraction. For example :

you can use

IDbCommand command = GiveMeSomeCommand();
IDataReader r = command.ExecuteReader();

without knowing which provider you are using

it can be:

private static IDbCommand GiveMeSomeCommand()
{
    return new OleDbCommand();
}

or it can be

private static IDbCommand GiveMeSomeCommand()
{
    return new SqlCommand();
}

or whatever.

EDIT:

You can also use the DBFactories.

DbProviderFactory factory = GiveMeSomeFactory();
IDbCommand command = factory.CreateCommand();
IDataReader r = command.ExecuteReader();

//and create more objects
IDataAdapter adapter = factory.CreateDataAdapter();
IDbConnection conn = factory.CreateConnection();

and then create your provider in other layer

private DbProviderFactory GiveMeSomeFactory()
{
    if(something)
        return SqlClientFactory.Instance;
    else if(somethingElse)
        return OracleFactory.Instance;
    else if(notThisAndNotThat)
        return MySqlFactory.Instance;
    else
        return WhateverFactory.Instance;

}
like image 121
Pablo Retyk Avatar answered Nov 15 '22 20:11

Pablo Retyk