dimanche 27 mai 2018

Validation required in multiple classes implementing the same interface

I have the following interface:

public interface IFoo
{
    void DoSmth(IList<int> list, string path);
}

There are also multiple derived classes that implement this interface and its single method. All of the classes need to validate the input parameters first, and only then do the actual job. Where should be that validation performed?

One solution is to write the validation code in each derived class, which causes code duplication.

The second and a better solution is to use an abstract base class and perform all the validation there. Something like this:

public abstract class BaseFoo
{
    public void DoSmth(IList<int> list, string path)
    {
        if(list == null)
        {
            throw new ArgumentNullException(nameof(list));
        }

        if(list.Count < 3)
        {
            return;
        }

        ...
        // more validation here
        ...

        InnerDoSmth(list, path);
    }

    protected abstract void InnerDoSmth(IList<int> list, string path);
}

Are there any design patterns and best practices for this case? Or it's ok to use a base class?

So where should I place the validation code?

Aucun commentaire:

Enregistrer un commentaire