Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interfaces for DTOs

Tags:

c#

interface

dto

I am currently at the beginning of developing a large web application mainly containing an Angular SPA and an OData WebAPI that has access to a backend layer.
We're at an early stage and have begun to implement the first classes including a Model.dll that is in a common namespace so that it can be accessed by all layers.
We are now discussing about those DTOs within the model. Some say that using interfaces is absolutely neccessary, so the code would be like this:

namespace MySolution.Common.Model
{
    public interface IPerson
    {
        int Id { get; set; }
        string Name { get; set; }
        ...
    }
}

namespace MySolution.Common.Model
{
    public class PersonDTO : IPerson
    {
        public int Id { get; set; }
        public string Name { get; set; }
        ...
    }
}

So that's it. Just simple DTOs with no more intelligence.
I am now asking myself if this is really a good approach, because I don't see the necessity of using the interface here.
What are the advantages with this? Testability was mentioned, but is it even necessary to test DTos? Dependency Injection should also not the point.
Any enlightenment would be very helpful. At the end learning new stuff and approaches is always good...

like image 451
Simon Linder Avatar asked May 19 '15 16:05

Simon Linder


2 Answers

DTOs transfer state - that's it. Injecting them via a container or mocking them for testing seems pointless (if that's the motivation) and totally unnecessary. Don't do it.

like image 126
Big Daddy Avatar answered Sep 17 '22 18:09

Big Daddy


As an example, further to my comment above:

Interface IRepo
{
  Person GetPerson(int id);
}

Public class DbRepo : IRepo
{
  public Person GetPerson(int id){//get person from database}
}

Public class FakeRepo : IRepo
{
  public Person GetPerson(int id)
  {
    return new Person {Id = id, Name = "TestName"};
  }
}

You would use a FakeRepo with some mock objects for testing purposes.

like image 43
Christian Phillips Avatar answered Sep 18 '22 18:09

Christian Phillips