Is returning IList worse than returning T[] or List?

前端 未结 5 2141
心在旅途
心在旅途 2020-12-12 12:38

The answers to questions like this: List or IList always seem to agree that returning an interface is better than returning a concrete implementation of a

5条回答
  •  庸人自扰
    2020-12-12 13:21

    Be careful with blanket quotes that are taken out of context.

    Returning an interface is better than returning a concrete implementation

    This quote only makes sense if it's used in the context of the SOLID principles. There are 5 principles but for the purposes of this discussion we'll just talk about the last 3.

    Dependency inversion principle

    one should “Depend upon Abstractions. Do not depend upon concretions.”

    In my opinion, this principle is the most difficult to understand. But if you look at the quote carefully it looks a lot like your original quote.

    Depend on interfaces (abstractions). Do no depend on concrete implementations (concretions).

    This is still a little confusing but if we start applying the other principles together it starts to make a lot more sense.

    Liskov substitution principle

    “objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.”

    As you pointed out, returning an Array is clearly different behavior to returning a List even though they both implement IList. This is most certainly a violation of LSP.

    The important thing to realize is that interfaces are about the consumer. If you're returning an interface, you've created a contract that any methods or properties on that interface can be used without changing the behavior of the program.

    Interface segregation principle

    “many client-specific interfaces are better than one general-purpose interface.”

    If you're returning an interface, you should return the most client specific interface your implementation supports. In other words, if you're not expecting the client to call the Add method you shouldn't return an interface with an Add method on it.

    Unfortunately, the interfaces in the .NET framework (particularly the early versions) are not always ideal client specific interfaces. Although as @Dennis pointed out in his answer, there are a lot more choices in .NET 4.5+.

提交回复
热议问题