How to decide on an api subscription

Many times when writing functions that accept enumerated types, I come across this confusion. Which api will be displayed will be the best of the following options:

public void Resolve(Func<bool>[] howtos) public void Resolve(IEnumerable<Func<bool>> howtos) public void Resolve(List<Func<bool>> howtos) 

I usually decide based on the following: if the input needs to be changed by adding or removing elements, use List else using IEnumerable. Not sure about Array option.

Are there other points to consider when deciding whether to open api? Is there any rule of thumb in which situations are clearly defined in which it should be preferable to another?

thanks

+4
source share
3 answers

You should always accept the least restrictive parameter types.

This means IEnumerable<T> , ICollection<T> or IList<T> .
Thus, the client can pass any kind of implementation, for example, an array, HashSet<T> or ReadOnlyCollection<T> .

In particular, you should take IEnumerable<T> if you only need to iterate over the data, ICollection<T> if you also want to add or remove elements, or if you need to know the size, and IList<T> if you need random access (index).

+4
source

The main factor for me in making this decision is

What is really doing with the collection?

If Resolve doesn’t mutate the collection, I would absolutely prefer the IEnumerable<Func<bool>> signature. This allows you to use the largest number of use cases and most accurately expresses the intent of the API. I would suggest that anything taking a more specific type of type List<T> intended to change what was passed to the collection. Vision IEnumerable<T> gives me a little certainty that the collection is simply enumerated.

If Resolve mutates a collection, I would prefer the List<T> signature to indicate that mutation is indeed possible. Perhaps I would create a free interface by grabbing and returning an IEnumerable<T> . Which will greatly depend on the type of Resolve method. It is difficult to generalize when I choose one over the other.

+2
source

Your path sounds good. The only thing I would change is IList<T> instead of List<T> . Allow the user, for example, to verify that you are adding to the list.

+1
source

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


All Articles