When do I use abstract classes versus interfaces with regards to dependency Injection?

前端 未结 6 921
名媛妹妹
名媛妹妹 2021-02-08 18:23

I have been reading some articles about the SOLID principles and dependency Inversion. From my point of view, I must use an interface to talk to any class. My classes are chatti

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-08 19:17

    I don't have a lot to add to the other answers provided, apart from some reasons to listen to them:

    An abstract class with only abstract methods is essentially an interface. The difference is that it could have some form of virtual implementation, and therein lies the trap: its all too easy when trying to reduce duplication using a base class to hide dependencies.

    Let's say you have a set of objects which need to persist between runs. It's tempting to add a save functionality to the base class so that no one else has to worry about how the save works. The problem is, if you totally hide it, you create a testing nightmare where the implementation has to be tested, or else a lot of functionality is relegated to only integration testing. Using Strategy for the save functionality would totally resolve the issue, and the two can be combined simply enough.

    The problem is more temptation than one simply being bad. Inheritance does not stop DI, but it doesn't encourage it either. If you're trying to get into SOLID and DI, you may be better off avoiding inheritance for now.

提交回复
热议问题