samedi 19 octobre 2019

The simplest way to use member methods of one class as member methods in another class without a duplication in C#

What is the simplest (architecturewise) way to use member methods of one class as member methods in another class without a duplication in C#?

E.g. I have the following class:

public class Person {
  public void go() { Console.WriteLine("go"); }
  public void jump() { Console.WriteLine("jump"); }
  public void buy() { Console.WriteLine("c"); }
}

And I have the following class:

public class Animal {
  public void go() { Console.WriteLine("go"); }
  public void jump() { Console.WriteLine("jump"); }
}

As you can see here the source code duplication happens. How could I avoid the duplication, given that I can not modify the class Person and I need to implement the class Animal with the same as above functionality and I would like to not have to update the class Animal once the method inside the Person is updated?

My considerations.

  • Since in Animal I do not need the buy() to be present and since the animal is not a person conceptually then the inheritance is not a choice (even though I could have changed the accessibility of the c() member to hide id). Also, I have a feeling that the inheritance is not the simplest solution here.

  • Another idea I have is to make an instance of the Person class to be a member field of the Animal class and just call the Person instance methods inside the Animal methods (e.g. in the Animal method: public void go() { this.person.go(); }), but again that is not a correct approach conceptually, since a person is not an attribute of an animal.

Notes

I am feeling that the best solution here should be something similar to the JavaScript mixins, where one can do the following:

var Person = function() {};
Person.prototype.go = function() { console.log("go"); };
Person.prototype.jump = function() { console.log("jump"); };
Person.prototype.buy = function() { console.log("buy"); };

var Animal  = function() {};
Animal.prototype.go = Person.prototype.go;
Animal.prototype.jump = Person.prototype.jump;

Is it possible to do something the same in C#? I performed the research on the internet about it and the only helpful thing I was able to find are the extension methods. But it is possible to use them only on instances of a type. That means that every time I create an animal I would have to also attach the extension methods to it, which does not look nice from an architecture point.

Aucun commentaire:

Enregistrer un commentaire