Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can one reduce the number of type parameters?

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());
    }
}
like image 379
William Jockusch Avatar asked Jan 16 '18 18:01

William Jockusch


1 Answers

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.

like image 177
Jon Skeet Avatar answered Nov 03 '22 20:11

Jon Skeet