How and when to use Interface?

Asked

Viewed 8,871 times

21

When should I use an interface, in which situations its use is feasible and which is not feasible and how to use it correctly?

I developed an example to illustrate a situation, below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace CONTROLLER
{
    public interface InterfaceController
    {
        bool Inserir() 
        {
            //Aqui segue a rotina de inserção.
        }

        bool Alterar() 
        {
            //Aqui segue a rotina de alteração.
        }

        bool Apagar() 
        {
            //Aqui segue a rotina de exclusão.
        }
    }
}

The interface InterfaceController above is part of the package CONTROLLER which is where the routines running operations in the database are, this interface is implemented in the class client in this way: public class Cliente : InterfaceController, below follows the class Cliente:

        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Text;
        using System.Threading.Tasks;
        using CONTROLLER;

        namespace MODEL
        {
            public class Cliente : InterfaceController
            {
                /*Aqui contera os atributos e os metodos de validação de regras
 *que por fim ira implementar os métodos da InterfaceController 
 *que executam operações no banco de dados.*/
            }
        }

The class Cliente this in the package MODEL responsible for validating business rules within the Cliente will contain the validation methods and attributes that represent a client, however, I do not have much experience in using Interfaces, do not know how to use and when to use interface, would like a help.

2 answers

14


It is difficult to say without knowing the specific case and mainly without knowing the requirements, the rules of the business or mechanism.

First obvious problems in the code

In addition to the name on ALL CAPS that does not follow the standard of C#, and the name InterfaceController Also not following, the biggest problem of this code seems to be having an interface that determines too many contracts. Most interfaces will have only one method, if more than one is probably dependent on the other or are closely interconnected.

Although they seem to be connected at first sight, I have my doubts. Again, it depends on the requirements that I do not know.

The controller really has to be a "full" CRUD? Maybe the problem is the name. Not all controller should have these methods. The interface is a contract that will have to be obeyed, it says what you need to implement in whichever class that makes use of it.

What shows another error, the code gives the impression that if it was real it should have a code within the interface methods. This is impossible in current C# but before interface methods could only be declared, they could not have a defined implementation.

Another name that is a little weird is the class. A Cliente should implement a controller? (See liskov principle). Wouldn’t it be better for a client’s controller to implement this? It may sound silly, but if you can’t define the right names for what each thing actually does in the code, it’s hard to write coherent code. I think one would be better ClienteController. Just like maybe there should be a ClienteModel. This yes maybe could even have the Model removed from the name since a client class can be exactly what would be in the customer model. But I question this in various situations.

It gets weirder to say that a namespace called CONTROLER (not only the caps which is bad, the name does not seem appropriate too), have "routines" that perform database operations. This should be something contained in the model or even something utilitarian, external to MVC. The controller should only control the interaction between the model and vision through requirements likely triggered by vision. And a class that implements the controller is in a namespace called MODEL? Very odd.

It seems to me that Inserir(), Alterar() and Apagar() will make operations in the database and will not link the model and view as requests, do not seem to be actions of the controller. If that’s the case, it would make sense to be on the model, even though not everyone likes it. It depends on the ORM/DAL or other pattern you are using to manipulate the database (assuming there will be one).

But I don’t want to go into that much here, because the question isn’t about MVC. My suggestion is to study more about MVC first.

The specific example

As the example became quite troubled it becomes difficult to speak specifically. And maybe this is happening because it’s creating too much of a fictional example. That is, it has no requirements, then it is difficult to write anything coherent, anything could be valid.

Maybe you want to implement the standard Repository, but you need to see if it’s necessary. I may already use something that implements it, then just consume the existing interfaces and do not need to think about it all.

When to use the interface

It may sound like a stupid answer, but it’s amazing how much it’s needed for many people: you should use interface when you know how to use! Don’t fall for the nonsense of wearing it because you’re watching other people do it. If you don’t fully understand the concept and you don’t know how to make the right decisions, maybe it’s best not to go out and create interfaces. This goes for anything in programming, but it goes even further for codes that exist basically to organize other codes. Imagine the opposite effect you might have using the wrong way.

One good thing to do in the beginning is not to create interfaces and see when they are needed, when there are similarities between classes that allow something in common to be defined as a contract to be followed. VS has help to do this automatically. Just check the method(s) you want to have on the interface, and ask to extract for it. Then just put her statement in all classes that already implement (s) method(s) chosen to be part of it. Often this helps at least in the beginning. The observation of the concrete helps to see the abstract.

Of course, this has the disadvantage of not requiring prior planning, which is one of the main reasons to use the interface. Creating them makes you think about the problem you’re solving. But if you have no experience you will create things artificial and meaningless, you will only make the situation worse.

What good is it

In essence interfaces should exist when you need to ensure that certain types have a certain feature, because the latter will be needed at some point in the code and with the interface you have to tell the compiler that that type has this expected feature. Obviously the compiler will require you to implement the interface, it just can’t guarantee that you did it the right way, that it fulfills all that is expected. He can only guarantee that you wrote something about it, that you "implemented" something in an attempt to fulfill the contract.

So any method that expects to receive an interface can receive any object that implements it, the compiler leaves and rejects objects of types that do not do this.

Interface is a compiler thing to help generate correct code, nothing more. The interface itself "disappears" after compiled. Unless it is a modern interface that allows code implementation, then it is clear that the implementation does not disappear.

Complement

I strongly suggest making new examples, perhaps simpler with well thought out requirements to practice the use and ask here if it is right and what can be improved.

I won’t go into more detail because there is a lot of information about interfaces generally here on the site, some with good examples of how to use them:

  • 1

    "When to use the interface?" Answer: "you should use interface when you know how to use". This helps?

  • 2

    One day you’ll know it helps. Until then run behind.

9

When using an interface and in what situations its use is viable?

Follows some recommendations for use:

  • When there is a need to provide common functionalities for unrelated classes.
  • When there is a need to group objects based on common behaviors.
  • When there is need to introduce polymorphic behavior to classes since a class can implement more than one interface.
  • When there is need to provide an abstract view of a model that is immutable.
  • When there is need to create low coupling components, easy maintenance and connective components, since the implementation of an interface is separate from itself.
  • When there is a need for multiple inheritance, a class can implement multiple interfaces.

In which situations its use is not feasible or misused?

  • Do not interface to a specific feature. An interface shall define the common functionality that can be implemented by the classes of different modules or subsystems.
  • Make sure that your interface does not contain many methods. Defining many methods makes it difficult to implement the interface
  • Keep your interfaces focused on the problem you’re trying to solve and keep related tasks(methods) in one interface.
    Interfaces that have several unrelated tasks tend to be very difficult to implement in a class.
  • An interface containing unrelated tasks shall be spun off into another interface.

Example of use:

interface IAcesso 
{ 
   void Ler(); 
   void Escrever(); 
} 
interface IComprimir 
{ 
   void Comprimir(); 
   void Descomprimir(); 
}


public class Documento : IAcesso, IComprimir
{
    #region IAcesso
    public void Ler()
    {
        Console.WriteLine("Executando o método Ler da classe Documento para IAcesso");
    }
    public void Escrever()
    {
        Console.WriteLine("Executando o método Escrever da classe Documento para IAcesso");
    }
    #endregion // IAcesso
    #region IComprimir
    public void Comprimir()
    {
        Console.WriteLine("Executando o método Comprimir da classe Documento para IComprimir");
    }
    public void Descomprimir()
    {
        Console.WriteLine("Executando o método Descomprimir da clase Documento para IComprimir");
    }
    #endregion // IComprimir
} 

Commentary:

Based on the above concepts, and using the example of the question as an example, we can deduce:

The interface InterfaceController does not have behavior common to its model classes, perhaps it would be better implemented by a data access class. (It is only opinion without knowing the concrete scenario)



Source: http://www.macoratti.net/14/04/c_intf1.htm

  • 4

    This answer seeks to actually answer the question, listing when to use it and when not to use it. (This taking one or another point that, because it is not accompanied by evidence, is difficult to assimilate (it seems like opinion).

  • I like your opinion, I will try to illustrate some points to improve the answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.