0

My application makes use of factory helpers for provisioning various objects. Each factory implements an interface, which allows it to be mocked to aid testing. Traditionally, each factory would be a class that implements the interface:

interface IRequestFactory {
    create(event: AWSLambda.APIGatewayProxyEvent): IRequest
}

class RealRequestFactory implements IRequestFactory {
    public create(event: AWSLambda.APIGatewayProxyEvent): RealRequest {
        return new RealRequest(event)
    }
}

class MockRequestFactory implements IRequestFactory {
    public create(event: AWSLambda.APIGatewayProxyEvent): MockRequest {
        return new MockRequest(event)
    }
}

RealRequestFactory, or MockRequestFactory can be instantiated and injected into other classes as a dependency. TypeScript however, allows us to declare anything as the interface type, so this can be done:

const realRequestFactory: IRequestFactory = {
    create(event: AWSLambda.APIGatewayProxyEvent): Request {
        return new Request(event)
    }
}

In this case, I don't need to instantiate a class, and can still inject realRequestFactory as a dependency of type IRequestFactory. This approach seems simpler, but I'm not sure it would be considered best practice because it feels a bit like a singleton.

Is there a consensus for typing non-classes against interfaces?

Ben Guest
  • 1,488
  • 2
  • 17
  • 29
  • 1
    Ok very short answer, from observing code in the wild I have to say that there doesn't seem to be any consensus on what the correct way to do this things is. One would argue that actual classes implementing interfaces is the more OOP way but another could argue that "duck-typing" is a major advantage that comes with writing things in JavaScript/TypeScript. – apokryfos Mar 13 '19 at 11:51
  • 1
    Okay thanks for the response. I think I will stick with the class way as it is more familiar in other OO languages – Ben Guest Mar 13 '19 at 12:19

1 Answers1

1

It's a singleton and yes singleton is considered an anti-pattern so class is better for testing and injection via Dependencji Injection Container

wookieb
  • 4,099
  • 1
  • 14
  • 17