How many constructors should a class have?

前端 未结 16 2310
一向
一向 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:02

    If you arbitrarily limit the number of constructors in a class, you could end up with a constructor that has a massive number of arguments. I would take a class with 100 constructors over a constructor with 100 arguments everyday. When you have a lot of constructors, you can choose to ignore most of them, but you can't ignore method arguments.

    Think of the set of constructors in a class as a mathematical function mapping M sets (where each set is a single constructor's argument list) to N instances of the given class. Now say, class Bar can take a Foo in one of its constructors, and class Foo takes a Baz as a constructor argument as we show here:

        Foo --> Bar
        Baz --> Foo
    

    We have the option of adding another constructor to Bar such that:

        Foo --> Bar
        Baz --> Bar
        Baz --> Foo
    

    This can be convenient for users of the Bar class, but since we already have a path from Baz to Bar (through Foo), we don't need that additional constructor. Hence, this is where the judgement call resides.

    But if we suddenly add a new class called Qux and we find ourselves in need to create an instance of Bar from it: we have to add a constructor somewhere. So it could either be:

        Foo --> Bar
        Baz --> Bar
        Qux --> Bar
        Baz --> Foo
    

    OR:

        Foo --> Bar
        Baz --> Bar
        Baz --> Foo
        Qux --> Foo
    

    The later would have a more even distribution of constructors between the classes but whether it is a better solution depends largely on the way in which they are going to be used.

提交回复
热议问题