Dependency Injections with Mutable Objects

跟風遠走 提交于 2020-07-23 03:34:15

问题


Would it be a bad idea to pass anything that could possibly not work in the future to a class?

For instance, passing a database connection (or anything that can possibly have it's methods rendered useless) to multiple classes? With JavaScript, these are passed by reference, therefore if the database connection is canceled outside of the class, the object within the classes wouldn't work? Now would this be bad, seeing now that all the models and things which use the database in methods will not work (without any notice that all the classes using the object now cannot be used).


回答1:


A database connection is a perfect example of something to pass into a class for dependency injection.

Dependency injection is useful for testing your models/classes, and during testing you want to "mock" certain services such as your database. In your tests, instead of "injecting" a database object, you would "inject" a mock object that models your database functionality.



来源:https://stackoverflow.com/questions/24252904/dependency-injections-with-mutable-objects

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