C# Interfaces – How to Enforce Implementation to Behave a Certain Way

cinterfacesnetobject-oriented-design

Suppose you had the following interface

public interface IUserRepository
{
    User GetByID(int userID);
}

How would you enforce implementers of this interface to throw an exception if a user is not found?

I suspect it's not possible to do with code alone, so how would you enforce implementers to implement the intended behavior? Be it through code, documentation, etc.?

In this example, the concrete implementation is expected to throw a UserNotFoundException

public class SomeClass
{
    private readonly IUserRepository _userRepository;

    public SomeClass(IUserRepository userRepository)
    {
        _userRepository = userRepository;
    }

    public void DisplayUser()
    {
        try 
        {
            var user = _userRepository.GetByID(5);
            MessageBox.Show("Hello " + user.Name);
        }
        catch (UserNotFoundException)
        {
            MessageBox.Show("User not found");
        }
    }
}

Best Answer

This is a language feature that was intentionally omitted from C#. Quite simply, it's entirely possible for an IUserRepository.GetByID to fail for some other reason entirely than the user not being found, so you don't want to require a specific error when such cannot happen. You have two options if for whatever reason you want to enforce this behavior:

  1. Define the User class so that it itself throws the exception if it's improperly initalized.
  2. Write unit tests for IUserRepository that explicitly test for this behavior.

Note that neither of those options is "include it in the documentation." Ideally, you should do that anyway, especially as documentation is where you can explain why you want to enforce a particular error type.

Related Topic