tags:

views:

109

answers:

3

While I was programming I came up with this question,

What is better, having a method accept a single entity or a List of those entity's?

For example I need a List of strings. I can either have:

  • a method accepting a List and return a List of strings with the results.

    List<string> results = methodwithlist(List[objects]); 
    

or

  • a method accepting a object and return a string. Then use this function in a loop and so filling a list.

    for int i = 0; i < List<objects>.Count;i++;)
    {
       results = methodwithsingleobject(List<objects>[i]);
    }
    

** This is just a example. I need to know which one is better, or more used and why.

Thanks!

+7  A: 

Well, it's easy to build the first form when you've got the second - but using LINQ, you really don't need to write your own, once you've got the projection. For example, you could write:

List<string> results = objectList.Select(X => MethodWithSingleObject()).ToList();

Generally it's easier to write and test a method which only deals with a single value, unless it actually needs to know the rest of the values in the collection (e.g. to find aggregates).

Jon Skeet
yes, exactly what I was thinking :-)
Alois Cochard
+2  A: 

I would choose the second because it's easier to use when you have a single string (i.e. it's more general purpose). Also, the responsibility of the method itself is more clear because the method should not have anything to do with lists if it's purpose is just to modify a string.

Also, you can simplify the call with Linq:

result = yourList.Select(p => methodwithsingleobject(p));
Pieter
+1  A: 

This question comes up a lot when learning any language, the answer is somewhat moot since the standard coding practice is to rely upon LINQ to optimize the code for you at runtime. But this presumes you're using a version of the language that supports it. But if you do want to do some research on this there are a few Stack Overflow articles that delve into this and also give external resources to review:

  1. http://stackoverflow.com/questions/365615/in-net-which-loop-runs-faster-for-or-foreach
  2. http://stackoverflow.com/questions/303343/c-for-loops-and-speed-test-exact-same-loop-faster-second-time-around

What I have learned, though, is not to rely too heavily on Count and to use Length on typed Collections as that can be a lot faster.

Hope this is helpful.

Liam