Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I'm this close to having an Interface epiphany

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?

like image 696
ItsPronounced Avatar asked Nov 28 '22 15:11

ItsPronounced


2 Answers

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

like image 85
Pete Avatar answered Dec 05 '22 01:12

Pete


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.

like image 33
Noon Silk Avatar answered Dec 05 '22 00:12

Noon Silk