Static factory methods vs Instance (normal) constructors?

前端 未结 11 1458
醉梦人生
醉梦人生 2020-12-02 12:16

In a language where both are available, would you prefer to see an instance constructor or a static method that returns an instance?

For example, if you\'re creating

11条回答
  •  抹茶落季
    2020-12-02 12:57

    I write a constructor when creating the instance has no side effects, i.e. when the only thing the constructor is doing is initializing properties. I write a static method (and make the constructor private) if creating the instance does something that you wouldn't ordinarily expect a constructor to do.

    For example:

    public class Foo
    {
       private Foo() { }
    
       private static List FooList = new List();
       public static Foo CreateFoo()
       {
          Foo f = new Foo();
          FooList.Add(f);
          return f;
       }
    }
    

    Because I adhere to this convention, if I see

    Foo f = Foo.CreateFoo();
    Bar b = new Bar();
    

    while reading my code, I have a very different set of expectations about what each of those two lines is doing. That code isn't telling me what it is that makes creating a Foo different from creating a Bar, but it's telling me that I need to look.

提交回复
热议问题