Is it better to use List or Collection?

前端 未结 8 690
失恋的感觉
失恋的感觉 2021-02-03 19:33

I have an object that stores some data in a list. The implementation could change later, and I don\'t want to expose the internal implementation to the end user. However, the us

8条回答
  •  无人及你
    2021-02-03 20:33

    Yes, your first alternative does leak implementation details if it's not part of your interface contract that the method will always return a List. Also, allowing user code to replace your collection instance is somewhat dangerous, because the implementation they pass in may not behave as you expect.

    Of course, it's all a matter of how much you trust your users. If you take the Python philosophy that "we're all consenting adults here" then the first method is just fine. If you think that your library will be used by inexperienced developers and you need to do all you can to "babysit" them and make sure they don't do something wrong then it's preferable not to let them set the collection and not to even return the actual collection. Instead return a (shallow) copy of it.

提交回复
热议问题