So to get it out of the way: polymorphism is great. Super useful. More than that – Polymorphism is absolutely necessary to write pragmatic software. And OOP embraces polymorphism, so what is my problem? Well… The problem with polymorphism in OOP is… OOPers smoke too much polymorphism. They don’t know when to stop.

twcon^s1_&ref_url=https%3A%2F%2Fwww.notion.so%2FProblems-with-Clean-Code-OOP-93388d2dc63d40c7a9f5097616d2b8fb

Polymorphism is not exclusive to OOP. One can do polymorphism in the machine code (by calling function indirectly by address in a register), C (by calling function by function pointer), FP (functions are first-class), non-OOP languages (dyn Trait in Rust, interface in Go). I’m not aware of any modern mainstream programming language that does not support polymorphism.

https://www.youtube.com/watch?v=aq365yzrTVE


Dynamic vs Static (Dispatching)

I think of it as compile time polymorphism versus runtime polymorphism. The latter is less performant due to the layer of indirection, although that performance difference is negligible for most applications, while being far more flexible.

Virtual (dynamic) dispatch induces indirection, this has a cost for multiple reasons:

  • indirection is opaque: this inhibits inlining and constant propagation which are key enablers for many compiler optimizations
  • indirection has a runtime cost: if incorrectly predicted, you are looking at pipeline stalls and expensive memory fetches

https://dpc.pw/what-oop-gets-wrong-about-interfaces-and-polymorphism

https://stackoverflow.com/questions/28621980/what-are-the-actual-runtime-performance-costs-of-dynamic-dispatch



🌱 Back to Garden