C# Interfaces – Avoiding Duplicate Code with Interfaces for Similar Behaviors

cinterfaces

So a simple example i have:

public interface IFollow{
    Transform Target {get;}
    void LateUpdate();
}

public A : Monobehaviour , IFollow {

   public Transform Target {get; set;}
   public void LateUpdate(){
      //follow the target
   }
}

public B : Monobehaviour , IFollow {

   public Transform Target {get; set;}
   public void LateUpdate(){
      //follow the target [duplicate code as seen in A]
}

When you have lots of different objects that follow a target with the same logic the implemented interface forces you to write a lot of duplicate code.

It also doesn't make much sense to do it via a base class since not all objects will follow.

What's a cleaner way to do this without so much duplication ?

Encase any one wondered, Monobehaviour is a Unity3D thing, though not overly relevant to the question but thought i'd mention it.

Best Answer

You have two options:

  • Implement in a(n) (abstract) base class
  • Implement in a helper adapter

Make a base class, or an abstract base class that implements the common behavior, and inherit from that. This way your code lives in one place and isn't duplicated.

If a base class doesn't work for some reason, you could put the code into a adapter (or strategy) object that each class uses to implement the behavior, again moving the duplicated code to one place.

Related Topic