samedi 18 novembre 2023

Filtering inside a processing method vs. filtering outside

In my application I am processing a List of IMyInterface instances. Not all, but some of them in addition also implement IAnotherInterface. Note that IAnotherInterface not derives from IMyInterface. Following the Single Responsibility Principle, I have a separate class that processes the IMyInterfaces instances via a Process method. Now I am struggling with the design choice whether

  1. the signature should be Process(IEnumerable<IMyInterface> items) and I filter for IAnotherInterface inside this method
  2. or the signature should be Process(IEnumerable<IAnotherInterface> items), meaning the filtering has to be done outside the processing method by the "client".

To make it more clear, these are the two code options I am struggling between:

// alternative 1:
List<MyInterface> items = GetItems(); // code not shown here
foreach(var item in items)
{
    // do some other processing before, not shown here

    // pass items to Process(IEnumerable<IMyInterface> items)
    myProcessor.Process(items);                
            
    // do some other processing afterwards, not shown here
}

// or alternative 2:
List<MyInterface> items = GetItems(); // code not shown here
foreach (var item in items)
{
    // do some other processing before, not shown here

    // pass items to Process(IEnumerable<IAnotherInterface> items)
    // -> need to filter first
    var filteredItems = filterForIAnotherInterface(items);
    myProcessor.Process(filteredItems);

    // do some other processing afterwards, not shown here
}

Is there any good reasoning for choosing one over the other? My own thoughts are that alternative 1 is easier to use for the client, but then the Process method has to do filtering which adds some kind of an additional responsibility besides it's main responsibility. On the other hand, alternative 2 in some way makes the processing pipeline less readable I think.

Aucun commentaire:

Enregistrer un commentaire