.net Interface Explanation

I understand that an interface in .Net defines a contract between an interface and a class that inherits it. Having just received work on a project that heavily used the interface for the level of access to data, I was wondering., Think? When I had to add a new method to the DAL, I had to create a method signature in the interface, and also add it to the class that inherited the interface, and, of course, the method to DAL, thereby creating an “extra work”. What is the matter with interfaces and why do I want to create additional work for myself?

+3
source share
11 answers

How important is the interface?

, , .

, , List<T> .NET. List<T>, , , .

IList<T> IEnumerable<T>, List<T> LinkedList<T> ( -, ), , .

... Polymorphism.

+9

IMO , , , . , . : , .

+3

, ( , SQL Server CouchDB), ( ) , .

" " .

+3

.

, , , , . .

+2
        foreach (object obj in myArray)
        {
            // distroy all IDisposable objects
            if (obj is IDisposable)
                (obj as IDisposable).Dispose();

            // ends initialization of all ISupportInitialize objects
            else if (obj is ISupportInitialize)
                (obj as ISupportInitialize).EndInit();
        }

, , , , .

. , Animal s ( ) Eat. , , , , , ...

, IEatable:)...

+2

, , , , 1/2 .

, . , - .

, - .

+1

, , DAL, . .

, , IoC ( Castle Windsor ), .

0

, , , . 10 , , .

IFoo, , IFoo , Bar() . Bar() , .

0

, . , (, List<T>), (IList<T>) , .

, Injection Dependency .

0

- ( ) . DAL , , . , DAL SQL Server, MySQL. , MySQL, , DAL . , .

, , .

0

I can make my code more reliable using interfaces.

If I have a ManagerClass

public class PersonManager
{
  public PersonManager(IPersonRepository repository)
  {
    this.Repository = repository;
  }
  private IPersonRepository Repository{get;set;}

  public Person ChangeUsername(string username)
  {
    Person person = this.Repository.GetByUsername(username);
    person.Username = username;
    this.Repository.Save(person);
    return person;
  }
}

The release code will use a repository object that will call the database, but for my unit test I want to isolate the database dependency so that I can create a mock repository that implements my interface:

public class MockPersonRepository : IPersonRepository
{
   public Person GetByUsername(string username)
   {
      return new Person();
   }
   public void Save()
   {}
}

And when I write my unit test, I can pass the layout:

[Test]
public void ChangeUserName_NewUsername_ExpectUpdateUsername()
{
  //Arrange
  var manager = new PersonManager(new MockPersonManager());

  //Act
  Person person = manager.ChangeUsername("bob");

  //Assert
  Assert(AreEqual("bob", person.Username);
}

I now have a manager to verify that my ChangeUsername method has updated the username without talking to the database

0
source

Source: https://habr.com/ru/post/1727649/


All Articles