How many constructors should a class have?

前端 未结 16 1924
一向
一向 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 13:00

    I limit my class to only have one real constructor. I define the real constructor as the one that has a body. I then have other constructors that just delegate to the real one depending on their parameters. Basically, I'm chaining my constructors.

    Looking at your class, there are four constructors that has a body:

    public MyManager(ISomeManager someManager) //this one I added
    {
        this.someManager = someManager;
    }
    
    public MyManager(SomeClass someClass, DateTime someDate)
    {
        if (someClass != null)
           myHelper = new MyHelper(someOtherClass, someDate, "some param");
    }
    
    public MyManager(SomeOtherClass someOtherClass, DateTime someDate)
    {
        myHelper = new MyHelper(someOtherClass, someDate, "some param");
    }
    
    public MyManager(YetAnotherClass yetAnotherClass, DateTime someDate)
    {
        myHelper = new MyHelper(yetAnotherClass, someDate, "some param");
    }
    

    The first one is the one that you've added. The second one is similar to the last two but there is a conditional. The last two constructors are very similar, except for the type of parameter.

    I would try to find a way to create just one real constructor, making either the 3rd constructor delegate to the 4th or the other way around. I'm not really sure if the first constructor can even fit in as it is doing something quite different than the old constructors.

    If you are interested in this approach, try to find a copy of the Refactoring to Patterns book and then go to the Chain Constructors page.

提交回复
热议问题