Reputation: 85
I have one question. I have to do a method that fills a List < object > from a sql database. My question is:
It's better to do this:
List<Product> listProducts = new List<Product>();
listProducts = loadProducts();
//this code is in other class
public List<Product> loadProducts()
{
List<Product > listProduct = new List<Product> ();
//code
return listProduct
}
Or it's better this:
List<Product> listProducts = new List<Product>();
listProducts = loadProducts(listProducts);
//this code is in other class
public List<Product> loadProducts(List<Product> listProduct)
{
//Code
return listProduct
}
Sorry if it's a noob question but both of two works but I don't know which is more improved.
Thanks a lot.
Upvotes: 4
Views: 182
Reputation: 41
Considering that in any case you would like to pass an existing list (with stuff already there) to be incremented I like the first option since it's more readable
Upvotes: 0
Reputation: 811
The first option is better. The second option isn't bad if you make it a void function and put the list as a reference parameter, but option one is still better because there is nothing in the original list needed for the function.
Upvotes: 1
Reputation: 1493
Go for this
List<Product> listProducts = loadProducts();
//this code is in other class
public List<Product> loadProducts()
{
List<Product > listProduct = new List<Product> ();
//code
return listProduct
}
Upvotes: 4
Reputation: 54011
I'd go with the first approach.
It seems somewhat pointless to pass the method a list which will then be populated and returned.
Upvotes: 1
Reputation: 41256
Neither, really.
You should just go like so:
List<Product> listProducts = loadProducts();
Option 1 makes a new list only to overwrite it later. Option 2 needlessly passes a list to the method, which will just send it back out modified.
Upvotes: 7
Reputation: 245479
Your first option is much better. It has clear meaning and no side effects.
Your second option will both return the list as well as fill the list that was passed to it. I would consider the filling of the list I pass to be a side effect which is undesirable.
Upvotes: 1
Reputation: 85116
I prefer to return it. Unless there is something with the contents of the list when you send it, I don't really see a reason to pass it as a parameter.
Upvotes: 6