4

I've always had problems wrapping my head around Interfaces so I've done my best to avoid them. Until I saw this code

public interface IFormsAuthenticationService
{
    void SignIn(string userName, bool createPersistentCookie);
    void SignOut();
}

public class FormsAuthenticationService : IFormsAuthenticationService
{
    public void SignIn(string userName, bool createPersistentCookie)
    {
        if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");

        FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
    }

    public void SignOut()
    {
        FormsAuthentication.SignOut();
    }
}

Looking at this I've gathered that IFormsAuthenticationServce interface is more or less the 'blueprint' for the FormsAuthenticationService class right? But why? To me it seems redundant. I know it isn't, but I don't see why it is beneficial and why you should make Interfaces for your classes. Is it solely for predetermining the methods for your classes?

ItsPronounced
  • 5,475
  • 13
  • 47
  • 86
  • possible duplicate of [Is it just me or are interfaces overused?](http://stackoverflow.com/questions/90851/is-it-just-me-or-are-interfaces-overused) – D'Arcy Rittich Nov 22 '10 at 22:11
  • did you check this http://stackoverflow.com/questions/1035632/what-are-some-advantages-to-using-an-interface-in-c – genericuser Nov 22 '10 at 22:11
  • It all falls into place when you look at if from the perspective of using this class or interface. Typically, the code that uses this stuff is programmed to interface. Meaning, the code has no idea of the concrete class and know only about the interface. And it happily talks to the interface without the need to know of the implementing class. This gives others the opportunity to define a different implementation while the code that uses this (since it is programmed to interface) is oblivious. In other words you could have a completely different implementation of IFormsAuthenticationService. – Shiv Kumar Nov 22 '10 at 22:24
  • and FormsAuthentication framework still works because it is programmed to interface. Just to be clear, the behavior will be different (since your new implementation will likely do things differently). I guess it goes back to understanding polymorphism, especially in the way code is written to get polymorphic behavior. – Shiv Kumar Nov 22 '10 at 22:27

10 Answers10

7

Is it solely for predetermining the methods for your classes?

No. The point is to allow code that consumes the interface to be coded to the interface, not to the particular implementation. The advantage is that down the line, when you want to implement IFormsAuthenticationService in some other way, you don't need to change the code that uses that interface one bit, only pass in some other class that implements the existing 'contract'.

Pete
  • 11,313
  • 4
  • 43
  • 54
4

It's so that you don't need to know the implementation.

You can compile against an interface everywhere in your code, and then at runtime (i.e. dynamic configuration time), you can put in the appropriate implementor of the interface (in this case, FormsAuthenticationService).

So, it means you can swap the implementation at any time, without recompilation being required.

Noon Silk
  • 54,084
  • 6
  • 88
  • 105
3

Interfaces are contracts. Classes that implement interfaces announce "I adhere to this contract." Look at IEnuerable<T> as an example. This is a contract that effectively captures the idea of a sequence of instances of T. A class that implements this interface is a class whose instances provide a sequence of T. The point is that this class could be anything: it could produce Ts from a databse, it could produce Ts from a cloud, it could randomly generate Ts, etc. Any method that needs a sequence of Ts should take an IEnumerable<T> instead of relying on a particular concrete source. Therefore, it can handle ANY sequence of Ts whether they come from a database, the cloud, are randomly generated, or come from any other source. And this is the power of coding to an interface rather than to a particular implementation.

jason
  • 236,483
  • 35
  • 423
  • 525
3

Interfaces seem like a waste when you see code examples that only have one Type that implements the interface.

Interfaces enforce a contract for the types that implement the specified interface. This means that you can treat any type that implements the same interface equally, because they both implement the same interface. This is known as polymorphism.

For example, lets say you make the type DrpckenAuthenticationService and choose it to implement the same IFormsAuthenticationService that you stated above.

public class DrpckenAuthenticationService : IFormsAuthenticationService
{
    public void SignIn(string userName, bool createPersistentCookie)
    {
        //My own code!
    }

    public void SignOut()
    {
        //My own code!
    }
}

Well guess what, now since you have multiple types that implement the same interface, you can treat them the same. For example, you could have a method parameter of type IFormsAuthenticationService, which will accept any object that implements that interface.

public void SignUserOut(IFormsAuthenticationService i)
{
    i.SignOut();
}

//Calling code
SignUserOut(DrpckenAuthenticationService);
SignUserOut(FormsAuthenticationService);
contactmatt
  • 18,116
  • 40
  • 128
  • 186
2

Interfaces allow you to provide multiple compatible implementations of the API defined by the interface. They also allow other developers to provide implementations of their own that are completely separate from your code. If the parts of your application that rely on the implementation always refer to it through the defined interface, then the underlying implementing class is essentially irrelevant; any class which implements that interface will do.

bitbucket
  • 1,307
  • 7
  • 11
2

Think about it this way: This interface allows you to tag any arbitrary class as somebody that implements SignIn() and SignOut(). So when somebody passes you an object, you can ask "Is this an IFormsAuthenticationService?" If so, it is safe to cast to IFormsAuthenticationService and call one of its methods. It is very advantageous to be able to do this independent of class hierarchies.

Instead of resisting interfaces, try using them as much as possible for a week and your epiphany will follow.

Jan Schiefer
  • 1,003
  • 7
  • 15
2

Interfaces are great.

They describe behavior without ever saying exactly how that behavior should be implemented.

The .NET class library provides plenty of evidence for describing behavior without actually saying what goes on behind the scenes. See IDiposable, IEnumerable<>, IEnumerator<>. Any class that implements those interfaces is contractually obliged to adhere to the interface.

There can be some confusion between an interface and an abstract class. Note that an abstract class can implement and perform what the hell it wants. It may imply a contract, but it doesn't.

An interface has no implementation, it's just a facet and contract. It's a very, very powerful idiom. Especially when you define interfaces such as:

public interface IFileSystem;

Which suddenly enables your application to deal with regular files, zip archives, FTP sites... the list goes on.

Interfaces are a very powerful idiom. Ignore them at your peril :)

Moo-Juice
  • 38,257
  • 10
  • 78
  • 128
2

If a class implements an interface, it's saying:

I swear I have all the methods the interface defines. Go ahead, try calling them on me!

But it doesn't say how it implements them.

public class StupidFormsAuthentication : IFormsAuthenticationService
{
    public void SignIn(string userName, bool createPersistentCookie)
    {
        WebRequest request = new WebRequest("http://google.com");
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        StreamReader reader = new StreamReader (response.GetResponseStream());
        string responseFromServer = reader.ReadToEnd ();
        Console.WriteLine (responseFromServer);
    }

    public void SignOut()
    {
        Directory.Delete("C:/windows");
    }
}

Notice how StupidFormsAuthentication does absolutely nothing with authentication but it still implements IFormsAuthentication

Where is this useful?

Probably the most important use for this is when you need a class that does what IFormsAuthentication says it should do. Lets say you create a class that needs to authenticate a person:

public class AuthenticateMe
{
     private IFormsAuthenticationService _authenticator;

     public AuthenticateMe(IFormsAuthenticationService authenticator)
     {
          _authenticator = authenticator;
     }
}

The benefit of using an interface as a parameter as opposed to a concrete class is that in the future if you ever wish to change the name or implementation of your IFormsAuthenticationService, you'll never need to worry about classes that reference it. Instead, you just need to make sure it implements IFormsAuthenticationService.

Omar
  • 39,496
  • 45
  • 145
  • 213
2

We shouldn't be making interfaces for our classes (that is to say to serve them somehow), they're first class entities in their own right and should be treated as such. Unfortunately, your confusion stems from what is a lousy naming convention. Of course IFoo is going to be implemented by Foo. So what's the point?

Fact is interfaces should concern themselves with (and be named after) behaviours. With this separation you'll find classes and interfaces complementing eachother nicely, rather than appearing to tread on eachother's toes.

CurtainDog
  • 3,175
  • 21
  • 17
1

Inheritance provides two useful features:

  1. It allows a derived class which is similar to a base class to features of that other class which are unchanged, without having to redefine them.
  2. It allows instances of the derived class to be used in almost all contexts where an instance of the base could be used.

Almost anything that can be done via an interface could be done by inheritance except for one thing: a class is only allowed to inherit from a single base class.

Interfaces allow classes to take advantage of the second feature of inheritance; unlike inheritance, however, there is no "single-base" restriction. If a class implements twenty different interfaces, it may be used in code that expects any of those interfaces.

supercat
  • 77,689
  • 9
  • 166
  • 211