Implicit interface based on class - c#

I have a lot of classes in my business layer that have an interface which must always have the same methods and properties as the public methods and properties of my business class. This is a common scenario, as the interface is needed for dependency injection and mocking while unit testing.
It would be optimal if I could somehow define the interface as the same as the public methods and properties of a class. That way I don't have to copy paste method definitions from my implemented class to my interface all the time. I don't see any logical problem with this, but I know that it's not directly possible to do in C#.
Perhaps someone can come up with a reasonable way to accomplish this?
Here is an example. Here is an interface.
public interface IAccountBusiness
{
Guid GetAccountIdByDomain(string domain);
void CreateAccount(string accountType, string accountName);
}
Here is the implementation:
public class AccountBusiness : IAccountBusiness
{
public Guid GetAccountIdByDomain(string domain)
{
// Implementation
}
public void CreateAccount(string accountType, string accountName)
{
// Implementation
}
}
If I want to add a parameter more in CreateAccount, for example "Email", then I have to add it to both the interface and the business class. In this example it's a minor nuisance but in larger scale projects it's ... well ... still a minor nuisance, but it doesn't have to be.

Resharper's Change Signature refactoring allows you to do that easily:

Related

What is the practical usage of interface not directly implemented in class?

I think I have a very naive question here that I didn't knew before that it was even possible. Forgive me if my title question is a bit vague because I don't even know how to describe it. Here is the code that looks weird to me.
public interface IMyInterface
{
void ImplementMe();
}
public class StandAlone
{
public void ImplementMe()
{
Console.writeline("It works!");
}
}
public class SubClass : StandAlone, IMyInterface
{
// no need to implement IMyInterface here but it still work!!!
}
IMyInterface myInterface = new SubClass();
myInterface.ImplementMe(); // Output : "It works!"
I just want to know the following :
What is the right term to describe this approach?
What is the practical benefit of this kind of approach?
What kind of problem it tries to solve? or What scenario this will be applicable?
Well, first case that comes to my mind - when you don't own source code of StandAlone class, but later you decided to introduce interface which describes behavior of StandAlone class. E.g. for unit-testing (it's not best practice to mock code which you don't own, but sometimes it might be helpful) or you want to provide alternative implementation of StandAlone behavior in some cases. So either you have no options for unit-testing such code:
public class SUT
{
private readonly StandAlone dependency;
public SUT(StandAlone dependency)
{
this.dependency = dependency;
}
// ...
}
But if you'll introduce interface, you can actually switch to dependency from IMyInterface instead of StandAlone. And provide SubClass as implementation of interface with zero efforts.
public class SUT
{
private readonly IMyInterface dependency;
public SUT(IMyInterface dependency)
{
this.dependency = dependency;
}
// ...
}
But SubClass does implement the IMyInterface - it has all the required public members with the right signatures. There's no specific terminology since there's nothing weird about it.
In fact, some languages take this even further, and allow you to cast any object to an interface, as long as the class has the right members (and in yet more flexible languages, even if it doesn't).
The main benefit is again the same as any other way to use interfaces - it allows you to abstract the implementation away from the interface. It's just a shortcut to having to do an explicit interface implementation, something like:
class SubClass : BaseClass, IInterface
{
void IInterface.MyMethod()
{
base.MyMethod();
}
}
You might think that you could just implement the interface in the base class, but there's plenty of reasons why you wouldn't:
You don't want to maintain a public interface for the base class, it's just an internal class that shouldn't be exposed outside.
You don't have a way to change the base class to include the interface, so if you want to keep an inheritance chain, you must subclass and add the interface to the subclass.
The inferface contains some members that aren't contained in the BaseClass.
You'll probably find a couple more reasons if you try.
But the main point is: why not? You need a reason to do something (expand the definition of the base class instead of just the subclass). Adding abstraction everywhere along your codebase is rarely beneficial - you're trying to find a good trade-off between clarity of intent and clarity of implementation. An interface on a base class might help or hinder that.
One legitimate use of this pattern (Outside of simply the original programmer should have put the interface on the base class) could be that Standalone is in a 3rd party (or inaccessible) assembly, and IMyInterface was written in your own code to provide a Facade.
Consider this;
Your app wants to provide some functionality. You define an interface with method ImplementMe.
Standalone is in ThirdParty.dll and provides this exact method name (Perhaps you modelled your interface on that method name on purpose)
You subclass Standalone within your own code in order to implement your functionality.
Maybe you have a second way of implementing ImplementMe for which you have your onw class implementing your own interface. (public class MyOwnImplemetation : IMyInterface {... })
You could then use DI to instantiate the correct implementation of StandAlone or MyOwnImplemetation but treat them both as IMyInterface.
Not all classes are direct implementations of interfaces.
For example, let's put a good sample based on a simple class inheritance:
public class Person
{
public Guid Id { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
}
public class Employee : Person
{
}
Now, let's imagine that we need to store uniquely-identifiable objects in some common store where we don't care about the entities' types but just about they're uniquely-identifiable.
BTW, we consider that persons shouldn't be stored within such store, because they're not valid entities within our organization but they're just there to improve code reusability and don't repeat ourselves.
So we define an interface like this:
public interface ICanBeUniquelyIdentifiable
{
Guid Id { get; set; }
}
...and we don't implement it on Person but we do so on Employee:
// Now an employee is an actual object that can be uniquely identifiable,
// and this isn't true because Person has an Id property, but because
// Employee fulfills the contract!
public class Employee : Person, ICanBeUniquelyIdentifiable
{
}
Background
I would say that your reasoning should be that you implement interfaces where they really matter to be implemented, and reusability shouldn't be the key point when implementing interfaces.
Actually, you should implement interfaces on objects which should be accepted on some API and you just need a subset of the full type of a given object.

Dependency injection with interfaces or classes

I've been guilty of having a 1-to-1 relationship between my interfaces and concrete classes when using dependency injection. When I need to add a method to an interface, I end up breaking all the classes that implement the interface.
This is a simple example, but let's assume that I need to inject an ILogger into one of my classes.
public interface ILogger
{
void Info(string message);
}
public class Logger : ILogger
{
public void Info(string message) { }
}
Having a 1-to-1 relationship like this feels like a code smell. Since I only have a single implementation, are there any potentially issues if I create a class and mark the Info method as virtual to override in my tests instead of having to create an interface just for a single class?
public class Logger
{
public virtual void Info(string message)
{
// Log to file
}
}
If I needed another implementation, I can override the Info method:
public class SqlLogger : Logger
{
public override void Info(string message)
{
// Log to SQL
}
}
If each of these classes have specific properties or methods that would create a leaky abstraction, I could extract out a base class:
public class Logger
{
public virtual void Info(string message)
{
throw new NotImplementedException();
}
}
public class SqlLogger : Logger
{
public override void Info(string message) { }
}
public class FileLogger : Logger
{
public override void Info(string message) { }
}
The reason why I didn't mark the base class as abstract is because if I ever wanted to add another method, I wouldn't break existing implementations. For example, if my FileLogger needed a Debug method, I can update the base class Logger without breaking the existing SqlLogger.
public class Logger
{
public virtual void Info(string message)
{
throw new NotImplementedException();
}
public virtual void Debug(string message)
{
throw new NotImplementedException();
}
}
public class SqlLogger : Logger
{
public override void Info(string message) { }
}
public class FileLogger : Logger
{
public override void Info(string message) { }
public override void Debug(string message) { }
}
Again, this is a simple example, but when I should I prefer an interface?
The "Quick" Answer
I would stick with interfaces. They are designed to be contracts for consumption for external entities.
#JakubKonecki mentioned multiple inheritance. I think this is the biggest reason to stick with interfaces as it will become very apparent on the consumer side if you force them to take a base class... no one likes base classes being thrust upon them.
The Updated "Quick" Answer
You have stated issues with interface implementations outside your control. A good approach is to simply create a new interface inheriting from the old one and fix your own implementation. You can then notify the other teams that a new interface is available. Over time, you can deprecate older interfaces.
Don't forget you can use the support of explicit interface implementations to help maintain a nice divide between interfaces that are logically the same, but of different versions.
If you want all this to fit in with DI, then try not to define new interfaces and instead favour additions. Alternatively to limit client code changes, try to inherit new interfaces from old ones.
Implementation vs. Consumption
There is a difference between implementing the interface and consuming it. Adding a method breaks the implementation(s), but does not break the consumer.
Removing a method obviously breaks the consumer, but does not break the implementation - however you wouldn't do this if you are backwards-compatibility conscious for your consumers.
My Experiences
We frequently have a 1-to-1 relationship with interfaces. It is largely a formality but you occasionally get nice instances where interfaces are useful because we stub / mock test implementations, or we actually provide client-specific implementations. The fact that this frequently breaks that one implementation if we happen to change the interface isn't a code smell, in my opinion, it is simply how you work against interfaces.
Our interface-based approach is now standing us in good stead as we utilise techniques such as the factory pattern and elements of DI to improve an aged legacy code base. Testing was able to quickly take advantage of the fact that interfaces existed in the code base for many years before finding a "definitive" use (ie, not just 1-1 mappings with concrete classes).
Base Class Cons
Base classes are for sharing implementation details to common entities, the fact they are able to do something similar with sharing an API publicly is a by-product in my opinion. Interfaces are designed to share API publicly, so use them.
With base classes you could also potentially get leakage of implementation details, for example if you need to make something public for another part of the implementation to use. These are no conducive to maintaining a clean public API.
Breaking / Supporting Implementations
If you go down the interface route you may run into difficulty changing even the interface due to breaking contracts. Also, as you mention, you could break implementations outside of your control. There are two ways to tackle this problem:
State that you won't break consumers, but you won't support implementations.
State that once an interface is published, it is never changed.
I have witnessed the latter, I see it come in two guises:
Completely separate interfaces for any new stuff: MyInterfaceV1, MyInterfaceV2.
Interface inheritance: MyInterfaceV2 : MyInterfaceV1.
I personally wouldn't choose to go down this route, I would choose to not support implementations from breaking changes. But sometimes we don't have this choice.
Some Code
public interface IGetNames
{
List<string> GetNames();
}
// One option is to redefine the entire interface and use
// explicit interface implementations in your concrete classes.
public interface IGetMoreNames
{
List<string> GetNames();
List<string> GetMoreNames();
}
// Another option is to inherit.
public interface IGetMoreNames : IGetNames
{
List<string> GetMoreNames();
}
// A final option is to only define new stuff.
public interface IGetMoreNames
{
List<string> GetMoreNames();
}
Your ILogger interface is breaking the interface segregation principle when you start adding Debug, Error, and Critical methods besides Info. Take a look at the horrible Log4Net ILog interface and you'll know what I'm talking about.
Instead of creating a method per log severity, create a single method that takes a log object:
void Log(LogEntry entry);
This completely solves all of your problems, because:
LogEntry will be a simple DTO and you can add new properties to it, without breaking any client.
You can create a set of extension methods for your ILogger interface that map to that single Log method.
Here's an example of such extension method:
public static class LoggerExtensions
{
public static void Debug(this ILogger logger, string message)
{
logger.Log(new LogEntry(message)
{
Severity = LoggingSeverity.Debug,
});
}
public static void Info(this ILogger logger, string message)
{
logger.Log(new LogEntry(message)
{
Severity = LoggingSeverity.Information,
});
}
}
For a more detailed discussion on this design, please read this.
You should always prefer the interface.
Yes, in some cases you will have the same methods on class and interface, but in more complex scenarios you won't. Also remember, that there is no multiple inheritance in .NET.
You should keep your interfaces in a separate assembly and your classes should be internal.
Another benefit of coding against interfaces is an ability to easily mock them in unit tests.
I Prefer interfaces. Given stubs and mocks are also implementations (sort of), I always have at least two implementations of any interface. Also, Interfaces can be stubbed and mocked for tests.
Further, the contract angle that Adam Houldsworth mentions is very constructive. IMHO it makes the code cleaner than 1-1 implementations of interfaces make it smelly.

Interfaces vs. inheritance: which is better in this case?

Let's suppose I have a widget class:
struct Widget {
public Color Color { get; set; }
public int Frobbles { get; set; }
}
Now, I need to make a factory to create these widgets, so I build a WidgetFactory:
abstract class WidgetFactory {
public virtual Widget GetWidget();
}
As it turns out, you can make widgets out of several different materials, but the resulting widgets are pretty much the same. So, I have a few implementations of WidgetFactory:
class GoldWidgetFactory : WidgetFactory {
public GoldWidgetFactory(GoldMine goldmine) {
//...
}
public Widget GetWidget() {
Gold g = goldmine.getGold();
//...
}
}
class XMLWidgetFactory : WidgetFactory {
public XMLWidgetFactory(XmlDocument xmlsource) {
//...
}
public Widget GetWidget() {
XmlNode node = //whatever
//...
}
}
class MagicWidgetFactory : WidgetFactory {
public Widget GetWidget() {
//creates widget from nothing
}
}
My question is this: Should WidgetFactory be an abstract class, or an interface? I can see arguments in both directions:
Base class:
The implementations ARE WidgetFactories
They might be able to share functionality, (say, a List<Widget> WidgetFactory.GetAllWidgets() method)
Interface:
The implementations do not inherit any data or functionality from the parent
Their internal workings are completely different
Only one method is defined
To those answering, this does not (currently) parallel to any real-world problem, but if/when I need to implement this pattern, it would be good to know. Also, "it doesn't matter" is a valid answer.
Edit: I should point out why go through this in the first place. The hypothetical usage of this class hierarchy would be something like:
//create a widget factory
WidgetFactory factory = new GoldWidgetFactory(myGoldMine);
//get a widget for our own nefarious purposes
Widget widget = factory.GetWidget();
//this method needs a few widgets
ConsumeWidgets(factory);
So, having a GetGoldWidget() method in WidgetFactory is not a very good idea. Plus, perhaps advents in Widget technology allow us to add different and more exotic types of widgets in the future? It's easier and cleaner to add a new class to handle them than shoehorn a method into an existing class.
In the example that you have given WidgetFactory has absolutely no reason to be an abstract class since there are not shared attributes or methods between different implementations of the factory.
Even if there was shared functionality, it would be more idiomatic to make an interface and pass it around to the users of WidgetFactory, to reduce the mount of knowledge those components need to have about the factory.
The overall implementation is fine and is really an abstract factory pattern, the only addition I would do is IWidgetFactory:
public interface IWidgetFactory {
Widget GetWidget();
}
abstract class WidgetFactory : IWidgetFactory {
//common attributes and methods
}
//Defferent implementations can still inherit from the base abstract class
class GoldWidgetFactory : WidgetFactory {
public GoldWidgetFactory(GoldMine goldmine) {
//...
}
public Widget GetWidget() {
Gold g = goldmine.getGold();
//...
}
}
In this case I see no benefit to using an abstract class instead of an interface.
I would generally favour interfaces over abstract classes:
They don't use up your one opportunity at class inheritance
They can be easier to mock
They feel "purer" somehow (it's clear just from the interface what the implementer needs to provide; you don't need to check each method to see whether or not it's concrete, abstract, or virtual)
In this case, however, you could easily use a delegate as there's only a single method... basically a Func<Widget>.
I disagree with Larry's idea of just using a single factory to directly create all the widgets with separate methods - as you may want to pass the WidgetFactory as a dependency to another class which doesn't need to know about the source, but needs to call CreateWidget either at a different time or possibly multiple times.
However, you could have a single widget factory with multiple methods each returning a Func<Widget>. That would give the benefits of having a single factory class while also allowing for dependency injection of the "factory" notion.
Honestly, what ever else, besides the Concrete Factory classes, do you expect to inherit from WidgetFactory? Anything?... ever?
If not it probably doesn't ever matter.
If down the road you want to add common code between them all than an abstract class would be your best bet.
Also I don't really see the need for your factory methods to implement any other interface except that of your creation method. So it doesn't matter whether it's abstract or interface. It all comes down to whether in the future you will want to add additional functionality in the future to the abstract class.
You don't need inheritance or an interface or even more than one class. The single factory should make all different kinds of widgets ; you can just pass in the materials as a parameter to the create method. The idea is to hide the aspects of different construction of objects from the caller - by making a bunch of different classes you are exposing this, not hiding it.

Is there any way to create default property implementations for C# interfaces

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?
As you already found out, you cannot add properties through extension methods. If it's a matter of easing the tests, you could use a mocking framework like Moq to avoid having to implement those properties on each class that inherits from the interface.
There are a variety of ways to do this, I suppose. As suggested you may look at just creating a hierarchy so that these types of functions are handled by the base class.
You may, however, be interested in a code-generation solution using T4 Templates (from Microsoft).

NUnit - How to test all classes that implement a particular interface

If I have interface IFoo, and have several classes that implement it, what is the best/most elegant/cleverest way to test all those classes against the interface?
I'd like to reduce test code duplication, but still 'stay true' to the principles of Unit testing.
What would you consider best practice? I'm using NUnit, but I suppose examples from any Unit testing framework would be valid
If you have classes implement any one interface then they all need to implement the methods in that interface. In order to test these classes you need to create a unit test class for each of the classes.
Lets go with a smarter route instead; if your goal is to avoid code and test code duplication you might want to create an abstract class instead that handles the recurring code.
E.g. you have the following interface:
public interface IFoo {
public void CommonCode();
public void SpecificCode();
}
You might want to create an abstract class:
public abstract class AbstractFoo : IFoo {
public void CommonCode() {
SpecificCode();
}
public abstract void SpecificCode();
}
Testing that is easy; implement the abstract class in the test class either as an inner class:
[TestFixture]
public void TestClass {
private class TestFoo : AbstractFoo {
boolean hasCalledSpecificCode = false;
public void SpecificCode() {
hasCalledSpecificCode = true;
}
}
[Test]
public void testCommonCallsSpecificCode() {
TestFoo fooFighter = new TestFoo();
fooFighter.CommonCode();
Assert.That(fooFighter.hasCalledSpecificCode, Is.True());
}
}
...or let the test class extend the abstract class itself if that fits your fancy.
[TestFixture]
public void TestClass : AbstractFoo {
boolean hasCalledSpecificCode;
public void specificCode() {
hasCalledSpecificCode = true;
}
[Test]
public void testCommonCallsSpecificCode() {
AbstractFoo fooFighter = this;
hasCalledSpecificCode = false;
fooFighter.CommonCode();
Assert.That(fooFighter.hasCalledSpecificCode, Is.True());
}
}
Having an abstract class take care of common code that an interface implies gives a much cleaner code design.
I hope this makes sense to you.
As a side note, this is a common design pattern called the Template Method pattern. In the above example, the template method is the CommonCode method and SpecificCode is called a stub or a hook. The idea is that anyone can extend behavior without the need to know the behind the scenes stuff.
A lot of frameworks rely on this behavioral pattern, e.g. ASP.NET where you have to implement the hooks in a page or a user controls such as the generated Page_Load method which is called by the Load event, the template method calls the hooks behind the scenes. There are a lot more examples of this. Basically anything that you have to implement that is using the words "load", "init", or "render" is called by a template method.
I disagree with Jon Limjap when he says,
It is not a contract on either a.) how the method should be implemented and b.) what that method should be doing exactly (it only guarantees the return type), the two reasons that I glean would be your motive in wanting this kind of test.
There could be many parts of the contract not specified in the return type. A language-agnostic example:
public interface List {
// adds o and returns the list
public List add(Object o);
// removed the first occurrence of o and returns the list
public List remove(Object o);
}
Your unit tests on LinkedList, ArrayList, CircularlyLinkedList, and all the others should test not only that the lists themselves are returned, but also that they have been properly modified.
There was an earlier question on design-by-contract, which can help point you in the right direction on one way of DRYing up these tests.
If you don't want the overhead of contracts, I recommend test rigs, along the lines of what Spoike recommended:
abstract class BaseListTest {
abstract public List newListInstance();
public void testAddToList() {
// do some adding tests
}
public void testRemoveFromList() {
// do some removing tests
}
}
class ArrayListTest < BaseListTest {
List newListInstance() { new ArrayList(); }
public void arrayListSpecificTest1() {
// test something about ArrayLists beyond the List requirements
}
}
I don't think this is best practice.
The simple truth is that an interface is nothing more than a contract that a method is implemented. It is not a contract on either a.) how the method should be implemented and b.) what that method should be doing exactly (it only guarantees the return type), the two reasons that I glean would be your motive in wanting this kind of test.
If you really want to be in control of your method implementation, you have the option of:
Implementing it as a method in an abstract class, and inherit from that. You will still need to inherit it into a concrete class, but you are sure that unless it is explicitly overriden that method will do that correct thing.
In .NET 3.5/C# 3.0, implementing the method as an extension method referencing to the Interface
Example:
public static ReturnType MethodName (this IMyinterface myImplementation, SomeObject someParameter)
{
//method body goes here
}
Any implementation properly referencing to that extension method will emit precisely that extension method so you only need to test it once.
How about a hierarchy of [TestFixture]s classes? Put the common test code in the base test class and inherit it into child test classes..
When testing an interface or base class contract, I prefer to let the test framework automatically take care of finding all of the implementers. This lets you concentrate on the interface under test and be reasonably sure that all implementations will be tested, without having to do a lot of manual implementation.
For xUnit.net, I created a Type Resolver library to search for all implementations of a particular type (the xUnit.net extensions are just a thin wrapper over the Type Resolver functionality, so it can be adapted for use in other frameworks).
In MbUnit, you can use a CombinatorialTest with UsingImplementations attributes on the parameters.
For other frameworks, the base class pattern Spoike mentioned can be useful.
Beyond testing the basics of the interface, you should also test that each individual implementation follows its particular requirements.
I don't use NUnit but I have tested C++ interfaces. I would first test a TestFoo class which is a basic implementation of it to make sure the generic stuff works. Then you just need to test the stuff that is unique to each interface.

Categories

Resources