Specific Common Interfaces

I am refactoring all my repository interfaces of various types. Most of them contain very similar methods, such as "Add", "Update", but some of them have methods that make sense only for a certain type. This is a matter of best practice.

I was thinking about using generics to rectify the situation.

 public interface IRepository<T>
 {
      T Get(int id);
      void Add(T x);
 }

But now for specific methods. I could, of course, “subclass” the interface, but then I’m no better than before. I would have code like:

 IUserRepository<User> users;

One easy way would be if I had a few limitations like:

 public partial interface IRepository<T>
 {
      T Get(int id);
      void Add(T x);
 }

 public partial interface IRepository<T> where T: User
 {
      T Get(Guid id);
 }

 public partial interface IRepository<T> where T: Order
 {
      T Get(string hash);
 }

But the compiler complains about conflicting inheritance. Another way would be to limit the methods:

 public partial interface IRepository<T>
 {
      T Get(int id);
      void Add(T x);

      T Get(Guid id) where T: User;
      T Get(string hash) where T: Order;
 }

, . , , , .

, NotImplemented. .

, .

+3
2
public interface IRepository<TEntity, TId>
 {
      TEntity Get(TId id);
      void Add(T x);
 }

public class UserRepository : IRepository<User, Guid>
{
    public User Get( Guid id ) 
    {
        // ...
    }

    public void Add( User entity) 
    {
        // ...
    }
}

public class OrderRepository : IRepository<Order, string> 
{
    //...
}
+6

:

?

, , . , , .

+2

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


All Articles