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开发者_如何学C? Or use params?
Thanks.
There is one thing you can do:
BuildThings(params Thing[] things);
Which enables you to use:
BuildThings(thing1, thing2, thing3, ...);
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.
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});
}
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.
Purely from a 'clean code' point of view, this is perfectly ok. Although functionally the alternatives might or might not suit you better. For example, using params
forces the collection to be enumerated before the call as opposed to lazily enumerated inside the call.
I would consider two cases:
- to have those two methods, but in
BuildThing(Thing a)
I would useBuildThings(IEnumerable<Thing> things)
and pass IEnumerable with only one Thing - Create only one method with
params
This option have one drawback - you have to convert everyIEnumerable
toArray
(except of arrays of course) if you want to pass more then one argument.
I would go with params
solution probably.
精彩评论