Is it OK for a factory method to return null?

前端 未结 4 1066
余生分开走
余生分开走 2021-02-12 03:39

I\'m wondering about best practice here. Is it good practice for a factory method to return null if it can\'t create anything? Here\'s an example:

ICommand comma         


        
4条回答
  •  生来不讨喜
    2021-02-12 04:02

    I think it's potentially reasonable for a factory method to return null in some situations, but not if it's a method called CreateCommand. If it were GetCommand or FetchCommand, that might be okay... but a Create method should throw an exception on failure, I would suggest.

    Whether you really want it to return null in this situation depends on the bigger picture, of course. (Is there a reasonable null object implementation you could return instead, for example?)

提交回复
热议问题