2

I have seen usage of SelectListItem[] at BL, DAL etc. levels that are not in the aps.net MVC project.

I am inclined to use anything that is IEnumerable<KeyValuePair<string, string>> instead e.g. Dictionary<string,string> c.f. Creating the IEnumerable<KeyValuePair<string, string>> Objects with C#?

My reasons are not to add the extra dependency on Web.MVC when not needed and SelectListItem belongs to MVC context as it is heavier than IEnumerable<KeyValuePair<string, string>>

Are these legitimate reasons or there are counter points to above that one should consider.

Are there any well know principals that would prefer one over the other, e.g. is there a principal to reduce dependencies when not needed?

Community
  • 1
  • 1
jimjim
  • 2,414
  • 2
  • 26
  • 46
  • 1
    Programming against an interface will help to decouple components and improve reusability. Take a look at `IDictionary`, it's a cleaner signature than `IEnumerable>`. – Austin Drenski May 08 '17 at 04:18

1 Answers1

1

Programming to an interface will help to decouple components and improve reusability in larger systems.

Think about what it says to you when you see a method signature returning an IEnumerable<T> instead of an IList<T>.

You know the designer expected you to enumerate the result, and you can reasonably assume that they did not intend for you to mutate the result in place.

When designing a new component or library, I start by asking myself about the behavior I expect on either side of a method. Does the caller really need to supply an int[], or can I get by with an IEnumerable<int>?

Further, if I require the array, does that mean I'm pushing an opinion onto the consumer? "You should always give me an array, because I think arrays are better."

At the same time, if a method signature takes an IDictionary<TKey, TValue>, I can easily swap a Dictionary<TKey, TValue> for an ImmutableDictionary<TKey, TValue> if I decide that my code would benefit from some of the new(ish) immutable collections.

As for whether or not you should reduce your dependencies, I think that's a question for your team to reflect on in the context of the project requirements. But on the question of replacing concrete types with interfaces where applicable and beneficial: go for it.

Austin Drenski
  • 506
  • 4
  • 10