Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One parameter or many

I have two methods:

BuildThing(Thing a);
BuildThings(IEnumerable<Thing> things);

Is this good from a clean code point of view? Or is maybe it would be better to just use BuildThings and pass IEnumerable with only one Thing? Or use params?

Thanks.

like image 544
Vladimir Nani Avatar asked Apr 13 '11 07:04

Vladimir Nani


People also ask

How many parameters should a method have?

The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification - and then shouldn't be used anyway.

What are the types of parameters?

Supported parameter types are string, integer, Boolean, and array.

How many parameters can a function have?

Except for functions with variable-length argument lists, the number of arguments in a function call must be the same as the number of parameters in the function definition. This number can be zero. The maximum number of arguments (and corresponding parameters) is 253 for a single function.

How many types of parameters are there?

We can use all 4 types of parameters in one function.


4 Answers

There is one thing you can do:

BuildThings(params Thing[] things);

Which enables you to use:

BuildThings(thing1, thing2, thing3, ...);
like image 125
Mikael Östberg Avatar answered Nov 08 '22 19:11

Mikael Östberg


my personal preference is as follows

interface:

void Build(Thing thing);
void Build(IEnumerable<Thing> things);

implementation:

void Build(Thing thing)
{
    Build(new [] { thing });
}

void Build(IEnumerable<Thing> things)
{
    //do stuff
}

the reason I prefer to use this pattern is because it makes sure that you stay DRY whilst giving you the flexibility of having multiple overloads, unlike the params way where you'd have to convert any non-array enumerable to an array.

like image 27
Darko Z Avatar answered Nov 08 '22 20:11

Darko Z


params would not be a good solution for your methods.

i think its ok to have your 2 or more methods as long you have just one implementation.

public void BuildThing(Thing a)
{
    this.BuildThings(new List<Thing>(){a});
}
like image 24
blindmeis Avatar answered Nov 08 '22 18:11

blindmeis


The methods you supplied seem like a good practice. There might be different things you would want to do when you're only building a single instance rather than multiple instances.

I wouldn't use params because that forces you to create an array, if you have a list for example.

like image 25
yellowblood Avatar answered Nov 08 '22 19:11

yellowblood