Can one reduce the number of type parameters?
Asked Answered
R

1

18

I find it annoying that one has to specify the types of both Foo and FooFactory in the call to RunTest below. After all, if the test knows the type of the Factory, the type the Factory is creating is implied. Assuming I want to run a lot of different factory tests for factories of different classes, that's a lot of angle brackets, and it gets worse with richer type hierarchies. I'm wondering if it is possible to restructure this so that the test is more concise.

public class Foo
{
}

public interface IFactory<T>
{
    T Create();
}

public class FooFactory : IFactory<Foo>
{
    public Foo Create()
      => new Foo();
}

public class FactoryTest
{
    internal void RunTest<TFactory, T>(TFactory factory)
        where TFactory : IFactory<T>
    {
        T t = factory.Create();
        Assert.NotEqual(default(T), t);
    }

    [Fact]
    public void FooFactoryWorks()
    {
        RunTest<FooFactory, Foo>(new FooFactory());
    }
}
Roentgenograph answered 16/1, 2018 at 18:15 Comment(3)
Why not just RunTest<T>(TFactory<T> factory)?Cloraclorinda
@Cloraclorinda You mean IFactory<T> right?Consistence
@Consistence A factory to make T.. >_<Cloraclorinda
P
51

It's not clear that TFactory has to be a type parameter at all. I'd write this:

internal void RunTest<T>(IFactory<T> factory)
{
    T t = factory.Create();
    Assert.NotEqual(default(T), t);
}

Then you can just use:

RunTest(new FooFactory());

as Foo can be inferred by the compiler.

Prut answered 16/1, 2018 at 18:19 Comment(1)
@BitcoinMurderousManiac: You definitely shouldn't just go looking for my answers and upvote them all. That's serial voting, and will be automatically reversed.Prut

© 2022 - 2024 — McMap. All rights reserved.