One parameter or many

I have two methods:

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

Is this good from a pure code point of view? Or maybe it would be better to just use BuildThings and pass IEnumerable with just one Thing? Or use the options?

Thanks.

+6
source share
6 answers

my personal preferences are 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 template is because it ensures that you stay DRY , giving you the flexibility of having multiple overloads, unlike the params method where you will need to convert any non-zero array enumerable to an array.

+6
source

There is one thing you can do:

 BuildThings(params Thing[] things); 

What allows you to use:

 BuildThings(thing1, thing2, thing3, ...); 
+5
source

params will not be a good solution for your methods.

I think its normal to have 2 or more methods if you have only one implementation.

 public void BuildThing(Thing a) { this.BuildThings(new List<Thing>(){a}); } 
+2
source

The methods you presented seem like good practice. There may be different things that you would like to do when you build only one instance, and not several instances.

I would not use params , because it forces you to create an array if you have a list, for example.

+1
source

Purely in terms of "clean code", this is completely normal. Functionally, alternatives may or may not suit you better. For example, using params forces the assembly to list before the call, rather than lazily enumerate inside the call.

0
source

I would consider two cases:

  • to have these two methods, but in BuildThing(Thing a) I would use BuildThings(IEnumerable<Thing> things) and pass IEnumerable with only one Thing
  • Create only one method with params This parameter has one drawback - you need to convert all IEnumerable to Array (except for arrays, of course) if you want to pass more than one argument.

I would choose a params solution.

0
source

Source: https://habr.com/ru/post/885794/


All Articles