2 classes implement the same interface, duplicated code

I have an interface:

public interface IUser
{

}

And then 2 classes implementing this interface:

public class User : IUser 
{

}

public class AdminUser : IUser
{

}

Now the problem is that when implementing the method in the interface, there is duplicate code between User and AdminUser.

Can I imagine an abstract class that somehow implements common code between User and AdminUser?

I do not want AdminUser to inherit from the user.

+4
source share
6 answers

Yes. You can.

public abstract class BaseUser : IUser
{

}

public class User : BaseUser 
{

}

public class AdminUser : BaseUser
{

}
+13
source

Looks like you need to enter a class UserBase, which both Userand AdminUsercould derive from the fact that a general code

class UserBase : IUser { 

  // Shared Code

}

class User : UserBase { } 

class AdminUser : UserBase { } 
+4
source

User AdminUser


, User , AdminUser . , User AdminUser User AdminUser.

public interface IUser
{
    void SomeMethod();
}


public abstract class User : IUser
{
    public abstract void SomeMethod();
}

public class AdminUser : User
{
    public override void SomeMethod()
    {
        throw new NotImplementedException();
    }

}

public class NormalUser : User
{
    public override void SomeMethod()
    {
        throw new NotImplementedException();
    }

}
+3

, , .

, ,

,

+2

, , , , , . , IAuthorizeable IEnumerable. .

, , , , , . , , , .

. User , , , , , , .

:

class User
{
  private IAuthenticator authenticator;
  public string Name { get; set; }
  public Guid Id { get; set; }
  public User(string name, Guid id, IAuthenticator authenticator)
  {
    Name = name;
    Id = id;
    this.authenticator = authenticator;
  }
  public Rights Authenticate()
  {
    return authenticator.Authenticate(Name, Id);
  }
}

, :

public class WebAuthenticator : IAuthenticator
{
  public Rights Authenticate(string name, Guid id)
  {
    // Some web specific authentication logic
  }
}

:

[Flags]
public enum Rights
{
  None = 0, Read = 1, Write = 1 << 1, Execute = 1 << 2
}

, , . , , , , , .

+2

, : . .

, .

, . , , mix-in.

interface IFoo
{
  int MethodA() ;
  int MethodB() ;
}
class IFooMixin : IFoo
{
  public int MethodA() { ... }
  public int MethodB() { ... }
}
class Widget : IFoo
{
  private IFooMixin IFooImplementation = new IFooMixin() ;
  public int MethodA()
  {
     int rc ;
     // inject your specific behavior here
     rc = IFooImplementation.MethodA() ;
     // and/or inject it here
     return rc ;
  }
  public int MethodB()
  {
     int rc ;
     // inject your specific behavior here
     rc = IFooImplementation.MethodB() ;
     // and/or inject it here
     return rc ;
  }
+1

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


All Articles