How many constructors should a class have?

前端 未结 16 1853
一向
一向 2021-02-04 12:34

I\'m currently modifying a class that has 9 different constructors. Now overall I believe this class is very poorly designed... so I\'m wondering if it is poor design for a clas

16条回答
  •  有刺的猬
    2021-02-04 12:38

    The answer: 1 (with regards to injectables).

    Here's a brilliant article on the topic: Dependency Injection anti-pattern: multiple constructors

    Summarized, your class's constructor should be for injecting dependencies and your class should be open about its dependencies. A dependency is something your class needs. Not something it wants, or something it would like, but can do without. It's something it needs.

    So having optional constructor parameters, or overloaded constructors, makes no sense to me. Your sole public constructor should define your class's set of dependencies. It's the contract your class is offering, that says "If you give me an IDigitalCamera, an ISomethingWorthPhotographing and an IBananaForScale, I'll give you the best damn IPhotographWithScale you can imagine. But if you skimp on any of those things, you're on your own".

    Here's an article, by Mark Seemann, that goes into some of the finer reasons for having a canonical constructor: State Your Dependency Intent

提交回复
热议问题