Good or bad practice? Initializing objects in getter

前端 未结 9 1795

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条回答
  •  我在风中等你
    2020-12-07 07:48

    I think it depends on what you are initialising. I probably wouldn't do it for a list as the construction cost is quite small, so it can go in the constructor. But if it was a pre-populated list then I probably wouldn't until it was needed for the first time.

    Basically, if the cost of construction outweighs the cost of doing an conditional check on each access then lazy create it. If not, do it in the constructor.

提交回复
热议问题