4 ms·
If you can use C++20, I'd encourage you to look into using concepts. Since I've started using them, it feels like a much more natural choice than class hierarch
by _huayra_ 5y ago
If you can use C++20, I'd encourage you to look into using concepts. Since I've started using them, it feels like a much more natural choice than class hierarchies when one needs to enforce type constraints on interfaces.
Instead of making a parent class that has a few key methods you need (e.g. send, recv) with the signatures (e.g. takes a pointer, returns a number), one can encode the use of those functions in a concept (e.g. a "socket" concept). This decouples the implementation from the use in the method, with the one big advantage being that it is easily testable -> no more need to carefully craft type hierarchies to carefully be able to substitute some mock object when you can just directly call it!
OO hierarchies certainly still have their place (even though so many conference talks seem to be about getting rid of them), but I'm glad I can relegate them to a dark corner of my toolbox until I absolutely need them.
In fact, come to think of it C++ concepts are basically Rust traits!
- rhodysurf 5y agoYea for sure, it’s a lot like swift being protocol oriented too. It’s a major paradigm shift I have to enforce in my head manually still at this point tho
- terhechte 5y agoNote that you can do Swift's protocol oriented programming / portocol extensions in Rust, too: trait Test { fn value(&self) -> i32; } impl dyn Test { fn multiplied(&self) -> i32 { self.value() * 2 } }
- Yoric 5y agoWhat does `impl dyn` mean, exactly? That this only works for trait objects?
- ComputerGuru 5y agoThat it works for any type implementing the trait, via vtables. Otherwise, it’s a method specific to the particular type implementing the trait (a concrete implementation but distinct to the specific impl).