Robert Koritnik
Robert Koritnik

Reputation: 105029

How to refactor almost duplicate methods with generic types

I have a few methods that are practically the same except they have a different number of generic type parameters. Inner code is very very similar:

public Set[] CreateSet<TFirst, TSecond>(List<TFirst> first, List<TSecond> second)
{
    Set[] result = new Set[2];
    result[0] = CreateSet(first);
    result[1] = CreateSet(second);
    return result;
}

public Set[] CreateSet<TFirst, TSecond, TThird>(List<TFirst> first, List<TSecond> second, List<TThird> third)
{
    Set[] result = new Set[3];
    result[0] = CreateSet(first);
    result[1] = CreateSet(second);
    result[2] = CreateSet(third);
    return result;
}

...

And so on. I have these methods up to 7 generic type parameters. As you can see they're practically all the same except that they create a different size array of sets.

I don't like this code duplication so would it be possible to refactor this code into a single private method that these would internally call. Or should I consider any other way of doing this?

Upvotes: 2

Views: 180

Answers (1)

Lee
Lee

Reputation: 144136

Maybe you could create a builder for the set collection e.g.

public class SetCollectionBuilder
{
    private readonly List<Set> sets = new List<Set>();
    public SetCollectionBuilder Add<T>(List<T> list)
    {
        this.sets.Add(CreateSet(list));
        return this;
    }

    public Set[] Build()
    {
        return this.sets.ToArray();
    }
}

Then you could create an arbitrary collection like:

Set[] result = new SetCollectionBuilder()
    .Add(first)
    .Add(second)
    .Build();

Upvotes: 1

Related Questions