Good or bad practice? Initializing objects in getter

前端 未结 9 1773

I have a strange habit it seems... according to my co-worker at least. We\'ve been working on a small project together. The way I wrote the classes is (simplified example):<

9条回答
  •  -上瘾入骨i
    2020-12-07 07:45

    Are you sure Foo should be instantiating anything at all?

    To me it seems smelly (though not necessarily wrong) to let Foo instantiate anything at all. Unless it is Foo's express purpose to be a factory, it should not instantiate it's own collaborators, but instead get them injected in its constructor.

    If however Foo's purpose of being is to create instances of type Bar, then I don't see anything wrong with doing it lazily.

提交回复
热议问题