I like the technique of creating extension methods against interfaces to provide default functionality. One of the places it is very handy is in putting some meat on dummy classes for unit tests.
For example,
public interface IEmployee
{
IAddress Address { get; set; }
IAddress GetAddress();
void SetAddress(IAddress address);
}
public class Employee : IEmployee
{
// Complex production stuff here (causes DB access)
}
public class TestEmployee : IEmployee
{
// Simple unit testing stuff goes here (in memory only)
}
public static class EmployeeExtensions
{
public static IAddress GetAddress(this IEmployee employee)
{
// Some sort of magic (maybe using IOC)
// 'employee' can be either of type 'Employee' or of type 'TestEmployee'
}
public static void SetAddress(this IEmployee employee, IAddress address)
{
// Again with the magic
}
}
Ok, maybe not a great example but you get the idea...
The key is that GetAddress and SetAddress can be called against both Employee and TestEmployee without code support from either of them. Unfortunately, this feels a little more like Java than C#. What I would really love to do for both is to work directly with the Address property and have it do all the same magic that the methods do. What I want to avoid is having to write code in the concrete classes to do it (especially in TestEmployee).
Is there any way to provide default implementations for the Address property of IEmployee?
I know that C# properties are actually methods under the hood. Anyway of providing implementations for those somehow?
Could it be done in a different .NET language?