4 ms·
> There are surely cases where having an interface as an abstraction and multiple implementations makes sense. I think most people aren't aware of the alternat
by philippta 2mo ago
> There are surely cases where having an interface as an abstraction and multiple implementations makes sense.
I think most people aren't aware of the alternative, which is: A function that can call different implementations based on some other variable.
E.g. instead of having RealDB and MockDB type have a createUser() (method), you have a createUser() (function) that switches part of it's logic based on what DB is selected.
That's the prodecural way of achieving the same thing without needing a concept for virtual functions.
Casey explains this in the long discussion with Uncle Bob.
- aidos 2mo agoAre you suggesting something like this? def createUesr(db): if db is type1: behaviour1 if db is type2: behaviour2
- philippta 2mo agoSee Casey's code snippets here: https://github.com/unclebob/cmuratori-discussion/blob/main/cleancodeqa-2.md https://github.com/unclebob/cmuratori-discussion/blob/main/c...
- TheCoelacanth 2mo agoYes, but there's not a chance that there's a material difference in performance between those options because of virtual functions. Unless you're doing something really stupid, nothing other than the DB access is going to be worth optimizing. If those two options are accessing the DB in exactly the same way, then they will probably be within 1% of each other in performance.
- alerighi 2mo agoDepends, for example if the variable that selects between the two implementations is a compile time constant (#define or constexpr variable) the compiler can really remove the conditional and all the code of the choice that is not always selected leading to higher performance and smaller footprint.
- jdlshore 2mo agoIt doesn’t matter. You’re saving nanoseconds when a db access costs milliseconds. Better to focus on making the code easy to understand and change and focus your effort on optimizing the database.
- zeratax 2mo agoyou are hyperfocusing on a single example. there are contexts where it matters and others where it doesnt sure, but i dont think either approach is inherently easier to understand or maintain
- TheCoelacanth 2mo agoThe only context where the overhead of a virtual function call matters is in tight inner loops. That's by far the easiest place to apply the "write something simple and readable and then measure and see if you need to change it" approach, so it just plainly doesn't work as argument against that approach.