dimanche 14 juin 2020

C# How to implement polymorphism in a functional style

I have some OOP code that I am wanting to translate into a functional style, using only immutable types and with only freestanding (static) side-effect-free functions.

Let's say I have two existing classes Foo1 and Foo2, which each implements an interface IHasBar, which in turn defines a method Bar. Foo1 and Foo2 each have their own unique implementation of that method. Obviously, I can extract those two methods and define them as separate static functions, one taking a Foo1 as its first argument, the other taking a Foo2 (and I can also make them extension methods to get dot syntax).

But how best can I enumerate over a collection of type IHasBar, and invoke the appropriate Bar function for each instance? A naive solution is to create a third function named Bar, taking an IHasBar as its first param, and within the implementation test the parameter for whether it is actually a Foo1 or Foo2 and then either cast it, or delegate to the appropriate function explicitly. I don't like doing this.

I can envisage how I could solve the requirement using reflection, but am reluctant to go that route if I can avoid it.

Is there an obvious simpler/cleaner solution that I am missing?





Aucun commentaire:

Enregistrer un commentaire