Do we ever need to prefer constructors over static factory methods? If so, when?

送分小仙女□ 提交于 2019-12-03 12:20:59

static factories still have to call a constructor in the end. You can move most of the functionality into the static factory, but you cannot avoid using a constructor.

On the other hand for simple cases, you can have just a constructor without having a static factory.

Constructors are the only way to set final fields, which IMHO are preferable to non-final fields.

You can use constructors can in sub-classes. You cannot use static factories for a sub-class.

If you have a good dependency injection framework to build dependencies of a component, you may find that static factories don't add much.

I like the comment from one of the similar questions you highlighted:

(On how to decide if you should favour a factory method over a constructor),

"you need to decide what you're trying to accomplish. Either you don't want people to call your constructor (you're creating a singleton or a factory), or you don't mind (as in NumberFormat above, where they're initializing some objects for the convenience of the caller)"

To me, this means it is justified to use a constructor, where the factory method is not required. Without any need for a factory, it just makes the code harder to follow ("which exact sub-class is returned here?")

I'm in pretty strong agreement with Josh Bloch here, and he makes the case better than I could, but here are a few places where static factories aren't as appropriate:

  • When dependency injection is more sensible; DI systems (certainly Guice) tend to inject things through their constructors. In particular, DI is appropriate when you expect that the parameters of the constructor might change in the future.
  • When you specifically intend for people to write subclasses, and you're providing a skeleton for them to implement.

Constructors are boring, you know exactly where to search for them, you know the scope of them, they are somehow predictable. They are there to construct the object itself, not to do god-like jobs. If you are doing too much other stuff that has not much to do with constructing the object you know you are doing something wrong. And it is not possible to "heal" this just by renaming the method. So they tend to be more focused, "better" in code quality when you have not top-of-the-line developers. (When you have the latter the points I mentioned don't matter.)

Boring stuff. Let's do something more fun and intellectual challenging...

Just for the records: I don't neglect the points mentioned in the question and other answers, I just wanted to add this additional point.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!