3 ms·
Another reason is it can help make testing more simplified. Instead of having to use a library to perform mocking or stubbing of specific functions within the o
by pseudoramble 8y ago
Another reason is it can help make testing more simplified. Instead of having to use a library to perform mocking or stubbing of specific functions within the objects, you can pass in fake instances of objects that help exercise the test properly. So instead of trying to mess around with the internals of an inherited object structure, you just redefine the objects during testing to meet your needs.
In other words, objects are composed of their dependent objects. I think this is where the idea of dependency injection comes from (though I find dependency injection frameworks complicated often, that's another story).
- asimpletune 8y agoI can not more strongly endorse this reason. Building abstractions around useful/loosely coupled ways of encapsulating dependencies, as mentioned elsewhere in this thread "bottom up", is part of an organic process that evolves into getting design right. A huge "lever" that you can lean on in this process is being able to mock the things that you want, while also being able to use the "real" versions of the things that you want. This allows your code to pretty much always be testable and flexible. It takes some practice, but once you get it your code grows so much better.
- pseudoramble 8y ago> It takes some practice, but once you get it your code grows so much better. It's true. I had a bit of a roundabout journey to getting this idea. Studying CS, I learned a ton about implementation inheritance, and only a bit about composition - enough to sort of answer a question about it, but not really get the feeling. So overall I didn't use it much. When I started working, I saw implementation inheritance used a ton and got the impression that it really made things way too complex. There was more to the complexity than just this of course (design patterns everywhere, convoluted abstractions, strange monolith tools, etc) but it didn't help. Later I started learning about FP, where composition is just second nature, and frankly one of the main methods of abstraction you get. So learning how to compose things came from functions. Over the past few months I've come back to more OOP, and I've been using composition a whole lot more. And it does make a huge difference, and I don't think I've used any sort of inheritance for my own code at all at this point. So yeah, I agree and it is a journey.
- asimpletune 8y agoI love that description of your evolution and I’d say it was actually the same for me.