What interface should my service return? IQueryable, IList, IEnumerable?

后端 未结 7 2211
孤独总比滥情好
孤独总比滥情好 2021-01-31 23:26

Imagine I have a SearchService layer that has a method to search all cars starting with a certain string;

public static class Searcher{
    public IAnInterface&l         


        
相关标签:
7条回答
  • 2021-01-31 23:57

    My rule of thumb is as follows:

    If there is ever a chance that I can take the routine's core algorithm and refactor it in a way that I can use yield returns, I will go with IEnumerable<T>.

    For example, if my current implementation uses an array or a List<T> internally, but I know that, at least theoretically, I may want to and be capable of reworking it internally to do lazy evaluation, I'll return an IEnumerable<T>.

    I've found that the gains of returning IEnumerable<T> are definitely worth the hassle of using it.

    However, if the algorithm, in its very nature, is going to need to fully evaluate the results before returning (rare, but does happen), I will go with an IList<T>. Basically, if I'm already computing it, I'll return it. IList<T> implements IEnumerable<T>, so all of the LINQ-related use cases still work, but you lose the lazy evaluation. If I'm already forced to evaluate in advance, that's not a problem, though.

    I rarely return IQueryable. The only time I would use this interface is if I'm directly creating a queryable data access layer, or something similar. The overhead of using this is, in most cases, not worth the gains.

    However, if your goal is to always use a single interface (I don't necessarily agree with this goal), I would stick to IEnumerable<T>.

    0 讨论(0)
提交回复
热议问题