Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do I place common logic required in multiple classes implementing the same interface?

Tags:

c#

inheritance

Given the following interface:

public interface IFoo
{
    bool Foo(Person a, Person b);
}

and the following two implementations of the above:

public class KungFoo : IFoo
{
    public bool Foo(Person a, Person b)
    {
        if (a.IsAmateur || b.IsAmateur) // common logic
          return true;
        return false;
    }
}

public class KongFoo : IFoo
{
    public bool Foo(Person a, Person b)
    {
        if (a.IsAmateur || b.IsAmateur) // common logic
          return false;
        return true;
    }
}

where should I place the "common logic" (as commented in the code) so it is in just one place (e.g. as a Func) and does not need to be repeated (as is the case above) for multiple implementations?

Note that the example above is very trivial but the real-life "common logic" is more complicated and the Foo() method does something useful!

I hope the question is clear (and not already been answered elsewhere - I did do a search) but feel free to probe me for more details if required.

like image 678
Appulus Avatar asked Dec 27 '22 17:12

Appulus


2 Answers

In a common abstract class:

public interface IFoo
{
    bool Foo(Person a, Person b);
}

public abstract class FooBase : IFoo
{
    public virtual bool Foo(Person a, Person b)
    {
        if (a.IsAmateur || b.IsAmateur) // common logic
          return true;
        return false;
    }
}

public class KungFoo : FooBase
{

}

public class KongFoo : FooBase
{
    public override bool Foo(Person a, Person b)
    {
        // Some other logic if the common logic doesn't work for you here
    }
}
like image 148
Joel Etherton Avatar answered Feb 13 '23 04:02

Joel Etherton


You can use base classes for common methods, but your common logic (or business rule) can be externalised rather neatly using the Specification Pattern.

There's lots of wordy examples and white papers out there, read through them if you're okay with that sort of stuff (I find it a bit too academic orientated), but there does seem a good introduction at:

http://devlicio.us/blogs/jeff_perrin/archive/2006/12/13/the-specification-pattern.aspx

like image 21
Adrian Thompson Phillips Avatar answered Feb 13 '23 03:02

Adrian Thompson Phillips