Soylent Code

Soylent Code is People! It's peeeeople!

6 Simple Rules for Handling Collections.

Simple rules for handling collections. This applies mostly to static languages like C# and Java:

  1. Always use generics if you can. Especially in C# where there are major performance advantages.
  2. Methods should always accept the simplest abstraction of a collection as possible. Iterable in java, IEnumerable in C#. This gives classes using the method the most flexibility. If you don’t need it to be a list, don’t ask for one.
  3. When returning a list return the most fully functioning implementation you can (without going out of your way….this is a very loose rule).
  4. When returning collections; if you don’t want people to modify the list then return a Immutable/Readonly list…and let them know it. Don’t hide a Immutable list behind simple interfaces.
  5. If the collection you return gets passed around a lot, think about making it into a little class. This can either be a wrapper or just extending a collection type. This will let you tweek the implementation and show intent better.
  6. If #5 is applying to a hashtable, dictionary or map have an even lower tolerance for when you make it a class. I almost never expose a map publicly.