I think of this question every time I use inheritance in OOP-languages.
Suppose we have a hierarchy of classes:
class Parent { public abstract void Foo(); } class Child1 extends Parent { public void Foo() { // Implementation 1 } } class Child2 extends Parent { public void Foo() { // Implementation 2 } }
We could achieve the same thing by passing a callback to the base class constructor:
class Parent { public Parent(doFoo) { this.doFoo = doFoo; } public void Foo() { // Any other logic this.doFoo(); } } new Parent(() => { /* do the thing */ })
Even if I had many "overrideable" methods, I could create an options object to pass them as a group. This would give me a benefit of having less classes in the code base and therefore less "things" to think about during development. Besides, the parent class gets to decide when the callbacks are called, which excludes the possibility of forgetting super() calls, but still gives the same freedom as overrides.
On a more global scale, not using inheritance gives more possibilities for a language to drop subtyping support, which simplifies type inference and type checking.
So, when and why should we prefer method overriding over callbacks?
Any thoughts are appreciated!
submitted by /u/smthamazing
[link] [comments]
from Software Development – methodologies, techniques, and tools. Covering Agile, RUP, Waterfall + more! http://bit.ly/2WGbbR0