I'm close to having the nickname "Interface"

I've always had problems wrapping my head around interfaces, so I did 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 realized that the IFormsAuthenticationServce interface IFormsAuthenticationServce more or less the β€œplan” for the FormsAuthenticationService class. But why? To me this seems redundant. I know that this is not so, but I do not understand why it is beneficial and why you should create interfaces for your classes. Is this solely for predefined methods for your classes?

+4
source share
10 answers

Is it just to predefine methods for your classes?

No. The point is to allow code that uses an interface to encode the interface, not a specific implementation. The advantage is that along the line, when you want to implement IFormsAuthenticationService in some other way, you do not need to change the code that uses this interface one bit, just pass it to some other class that implements the existing "contract".

+7
source

This is so that you do not need to know the implementation.

You can compile the interface in all your code, and then at runtime (i.e. dynamic configuration time) you can put the appropriate interface constructor (in this case, FormsAuthenticationService).

So this means that you can change the implementation at any time without the need for recompilation.

+4
source

Interfaces are contracts. Classes that implement interfaces declare "I adhere to this contract." Take a 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 the sequence T The fact is that this class can be anything: it could generate T from the database, it could produce T from the cloud, it could randomly generate T s, etc. Any method that needs a T sequence should take IEnumerable<T> instead of relying on a specific, specific source. Therefore, it can process ANY sequence of T , regardless of whether they come from a database, clouds, are randomly generated, or come from any other source. And this is the coding strength for the interface, not for a specific implementation.

+3
source

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

Interfaces provide contract execution for types that implement the specified interface. This means that you can consider any type that implements the same interface in the same way, because they both implement the same interface. This is called polymorphism.

For example, suppose you create the DrpckenAuthenticationService type and select it to implement the same IFormsAuthenticationService standard that you specified above.

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

Guess that now that you have several types that implement the same interface , you can treat them the same way. For example, you may have a method parameter of type IFormsAuthenticationService that will accept any object that implements this interface.

 public void SignUserOut(IFormsAuthenticationService i) { i.SignOut(); } //Calling code SignUserOut(DrpckenAuthenticationService); SignUserOut(FormsAuthenticationService); 
+3
source

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

+2
source

Think of it this way: this interface allows you to mark any arbitrary class as a person that implements SignIn () and SignOut (). So when someone passes you an object, you may ask, "Is this an IFormsAuthenticationService?" If so, it is safe to pass in the IFormsAuthenticationService and call one of its methods. It is very beneficial to be able to do this regardless of the class hierarchy.

Instead of resisting the interfaces, try to use them as much as possible during the week, and your insight will follow.

+2
source

The interfaces are great.

They describe the behavior, not even saying exactly how this behavior should be implemented.

The .NET class library provides a wealth of evidence for describing behavior, not to mention what happens behind the scenes. See IDiposable , IEnumerable<> , IEnumerator<> . Any class that implements these interfaces is contractually required to adhere to the interface.

There may be some confusion between the interface and the abstract class. Note that an abstract class can implement and execute what it wants. It may mean a contract, but it is not.

The interface has no implementation, it's just a side and a contract. This is a very, very strong idiom. Especially when you define interfaces such as:

 public interface IFileSystem; 

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

Interfaces are a very powerful idiom. Ignore them if you are in danger :)

+2
source

If the class implements an interface, it says:

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

But he does not say how he 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"); } } 

Note that StupidFormsAuthentication does nothing with authentication, but still implements IFormsAuthentication

Where is this useful?

Perhaps the most important thing for this is when you need a class that does what IFormsAuthentication says it should do. Let's say you created a class that should authenticate a person:

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

The advantage of using an interface as a parameter as opposed to a particular class is that in the future, if you ever want to change the name or implementation of your IFormsAuthenticationService , you will never have to worry about the classes that reference It. Instead, you just need to make sure that it implements the IFormsAuthenticationService .

+2
source

We should not create interfaces for our classes (i.e., serve them in some way), they are first-class entities in their own right and should be considered as such. Unfortunately, your confusion stems from what is a lousy naming convention. Of course, IFoo will be implemented by Foo . So what is the point?

Fact - Interfaces must take care of behavior (and be named after). With this separation, you will find classes and interfaces complementing each other beautifully, instead of appearing at every step.

+2
source

Inheritance provides two useful features:

  1. It allows a derived class, similar to a base class, to functions of this other class that do not change, without having to redefine them.
  2. It allows instances of a derived class to be used in almost all contexts where a database instance can be used.

    Almost everything that can be done through the interface can be done by inheritance, except for one thing: a class is allowed to inherit from only one base class.

    Interfaces allow classes to use the second feature of inheritance; However, unlike inheritance, restrictions on one basic do not exist. If a class implements twenty different interfaces, it can be used in code that expects any of these interfaces.

+1
source

All Articles