Generic Decorator in C# - c#

I wonder since there is no way how to implement a generic Decorator class in C# (is it?) like this:
public class Decorator<TDecoratorIterface> : TDecoratorInterface
{
public TDecoratorInterface Component {get; private set;}
protected Decorator(TDecoratorInterface component)
{
Component = component;
}
}
use like this:
public interface IDogDecorator
{
void Bark();
}
public class Dog : IDogDecorator
{
public void Bark()
{
Console.Write("I am a dog");
}
}
public class StinkingDog : Decorator<IDogDecorator>
{
public StinkingDog(IDogDecorator dog):base(dog)
{
}
public void Bark()
{
Component.Bark();
Console.WriteLine(" and I stink");
}
}
can such a thing be managed via PostSharp or any other AOP framework for .NET?
thank fro your answers, I spent half a day trying to create such a construct without any success, so any help is appreciatted:)

There's no direct equivalent to this construct, as C# doesn't allow the base class of a type to be dynamic. Remember that the generic type must be fully defined at compile time, not at usage time.
There's multiple possible ways to go: In the example above, the StinkingDog should just implement the IDogDecorator interface. So just specify that there. You're forwarding calls anyway.
public class StinkingDog : Decorator<IDogDecorator>, IDogDecorator
There would probably be frameworks that do what you want exactly (i.e. Rhino.Mocks is actually creating Mocks this way), but for production code, I'd really suggest not doing any AOP approach. It's clumsy and slow.

Related

C# 8 default interface implementation and inheritance

I want to use C# 8 default interface implementation to face a performance issue in my code.
Actually, I have this intefaces :
public interface IDataAdapter {}
public interface IDataAdapter<T> : IDataAdapter
{
void Insert(T value);
}
I actually have to do reflection across all IDataAdapter, check generic type and call Insert by reflection for a specific T instance. What I wish to do is :
public interface IDataAdapter
{
void InsertValue(object value);
}
public interface IDataAdapter<T> : IDataAdapter
{
void Insert(T value);
public void InsertValue(object value) => Insert(value as T);
}
The compiler says to use the keyword new to mask the inherited method. However, the only thing I'm trying to accomplish is to have a non-generic method already implemented to make all IDataAdapter<T> implementations to only have to implement the generic version.
Is this something I can accomplish or it's still impossible ? I already know that using an abstract class is a way to solve this issue, but I want to allow a developper to have a class that implements many IDataAdapter...
This is my current reflection code :
public IEnumerable<IDataAdapter> DataAdapters { get; }
public Repository(IEnumerable<IDataAdapter> dataAdapters)
{
DataAdapters = dataAdapters;
}
public async Task SaveAsync()
{
foreach (var item in aggregates)
{
foreach (var dataAdapter in DataAdapters)
{
if (dataAdapter.GetType().GetInterfaces().Any(i => i.IsGenericType && i.GetGenericArguments()[0] == item.GetType()))
{
dataAdapter.GetType().GetMethod("Insert", new[] { item.GetType() }).Invoke(dataAdapter, new[] { item });
}
}
}
}
From an object oriented point of view, what you are trying to do can't be done.
Suppose you create the following class hierarchy:
public interface IFoo{}
public interface IBar{}
public class A: IFoo{}
public class B: IFoo{}
public class C:IFoo,IBar {}
And then the following adapters:
public class TestA : IDataAdapter<A>{}
public class TestB : IDataAdapter<B>{}
public class TestC : IDataAdapter<C>{}
public class TestIFoo : IDataAdapter<IFoo>{}
public class TestIBar : IDataAdapter<IBar>{}
public class TestIBoth : IDataAdapter<IFoo>,IDataAdapter<IBar>{}
What should happen if TestA receive an instance of A is quite easy. But what about TestIFoo receive a C? Currently your reflection code won't work because you test type equality (does C equals IFoo? No! Even if C as IFoo is ok).
This breaks Liskov substitution principle. If something works with a class then it should also work with any of its subclasses.
Let's suppose you fix above point. Now what about TestIBoth receiving a C? Is there two different implementation of Insert in it? Of course, this is required by inheritence! But then... do you have to insert C twice? Or do you have to insert it just once in the first fitting method?
The reason why you have to go through reflection is because all those questions needs an algorithmic answer. Your compiler won't be able to answer (which makes the language prevent it by the way)
In the end I would strongly recommend to use a very different solution (like the one proposed by Wim Coenen)
I recognize this problem where you need to look up the IDataAdapter implementation which knows how to handle a certain type of item. I've done something similar for a "view plugin" system, where I would look for the view plugin that knows how to render a certain type. This is useful if you can't know in advance what type of objects you'll need to render.
As far as I know, trying to shoehorn more compile-time type safety into this pattern won't really work, or if it does then it won't actually provide any benefits. I would just declare IDataAdapter like this:
public interface IDataAdapter
{
void InsertValue(object value);
Type SupportedType { get; }
}
If a data adapter supports multiple types, you can make it IEnumerable<Type> SupportedTypes instead, or maybe replace the property by a bool SupportsType(Type) method.

Open-Close principle about new features

There is something I do not understand about open-close principle. Let's say that you have done this code:
public abstract class Player
{
public string Name { get; set; }
public int Level { get; set; }
}
public sealed class Fighter : Player { /* ... */ }
public sealed class Warrior : Player { /* ... */ }
This code works perfectly, you've done a first release, eveyrthing is OK.
Now you want to add some features, like a player can equip a ring. Open-close principle says open to extension, close to modification. How could I implement the fact that my players can have rings if I shouldn't modify these class?
You can modify class Player by adding new methods and fields. It is open to extension. But if you already have some methods like Jump or Fight and you want to modify them - that is breaking the principle.
Imagine, your class Fighter has method Fight() and it uses only bare hands:
public Fighter() : Player
{
...
public virtual void Fight()
{
//use bare hands
}
}
If you want Fighter to fight with a stick (for example) you should not modify initial method Fight() but add another class like FighterWithStick : Fighter and override method Fight() there:
public FighterWithStick() : Fighter
{
...
public override void Fight()
{
//use stick
}
}
First think why this kind of rule might be useful. Closed to modification, open to extension. This makes sense for libraries or code that must be backwards compatible. Think of this example:
I've written "BestLibrary" library which exposes interface:
namespace BestLibrary
{
public interface GoodStuff
{
Goodies GiveMeGoodStuff();
}
}
But in the next release I want to decide what Goodies to give based on a parameter, so I change the interface to:
namespace BestLibrary
{
public interface GoodStuff
{
Goodies GiveMeGoodStuff(GoodiesType type);
}
}
public enum GoodiesType { All, Type1, Type2 }
Now everyone who uses my library has to fix their code, because their projects will stop building. This brakes Open/Closed principle. Instead I should make another method, like this:
namespace BestLibrary
{
public interface GoodStuff
{
Goodies GiveMeGoodStuff();
Goodies GiveMeGoodStuff(GoodiesType type);
}
}
Here I didn't modify anything. Old code still works. Someone wants random Goodies? They can still get it. I extended GoodStuff interface with additional method. This way everything compiles and people can use new functionality.
If you work on a project that is not a library or api, then I don't see any reason to follow this principle. Requirements change and code should follow.

Is it possible to implement classes with modular methods?

I am trying to create an object that can call one of 3 methods in response to user input. Let's call them, DoShape, DoColor, and DoPowerTool. These methods exist as part of a base class and interfaces respectively:
Public Class PowerTool
{
...
public virtual void DoPowerTool()
{
...
}
}
Public Interface Shape
{
void DoShape(PowerTool p);
}
Public Interface Color
{
void DoColor(PowerTool p);
}
As DoShape and DoColor require a PowerTool, the intuitive thing would be to somehow bake those methods into the PowerTool instance itself.
Unfortunately, I can't have the PowerTool class implement Shape and Color directly, since I won't know until runtime if it's a Red Square Jackahmmer or a Green Ovoid one.
I've dabbled with C#'s delegates, and have a feeling that they might be useful in this case, but I'm not familiar enough to know how to implement them in this precise scenario, and I'm unsure if they're the right choice to give me the modular behavior I'm looking for. (I may be spoiled by Javascript in this regard, where you can simply overwrite functions on objects).
Any thoughts or suggestions on how to continue? I feel like there's probably a very simple solution that I'm overlooking in all this.
A relatively simple way to do what you're talking about (from what I can tell) would be to simply have 3 interfaces:
public interface IPowerTool : IShape, IColor
{
void Execute();
}
Thus, you can simply define:
public RedSquareJackhammer : IPowerTool
{
void DoShape() {}
void DoColor() {}
void Execute() {}
}
Another option is to do this:
public PowerTool
{
IColor color;
IShape shape;
public PowerTool(IColor c, IShape s) {
color = c; share = s;
}
void Execute() {
color.DoColor();
shape.DoShape();
}
}
Then you call it like this:
// JackHammer is derived from PowerTool, Red from IColor, Square from IShape
var redSquareJackhammer = new JackHammer(new Red(), new Square());
Etc.. there are many ways to skin this cat.
I believe what you are referring to is the concept of a Mixin.
This is where one or many implementations for an interface are defined, and then the implementations are reused for their concrete types.
This is unfortunately not really possible in .NET because the framework was desgined without that ability to use multiple inheritance. Though, you may be able to replicate the behavior you're seeking using extension methods or, through dependency injection and the strategy pattern.
If you have any further questions about the patterns, or require more applicable examples, just let me know what you're attempting to accomplish in more detail and I will do my best to help.
If I understand what you are describing, the following strategy pattern may be of benefit:
internal interface IPowerToolStrategy
{
void Execute(PowerTool powerTool);
}
public class RedSquareJackhammer : IShape
{
private readonly IPowerToolStrategy _strategy;
internal RedSquareJackhammer(IPowerToolStrategy strategy)
{
_strategy = strategy;
}
public void DoShape(PowerTool powerTool)
{
_strategy.Execute(powerTool);
}
}

Letting only the abstract class know about its inheritors

I am making a payment system for my site. Users can select one of several payment providers to pay, but all should behave in the same way. I thought to represent this behavior like this:
public abstract class PaymentProvider {
private static var methods = Dictionary<String,PaymentProvider>
{
{"paypal",new PaymentProviderPaypal()},
{"worldpay",new PaymentProviderWorldpay()}
}
public static Dictionary<String,PaymentProvider> AllPaymentProviders
{
get {return methods;}
}
public abstract pay();
}
public class PaymentProviderPaypal : PaymentProvider {
public override pay() {
}
}
public class PaymentProviderWorldpay : PaymentProvider {
public override pay() {
}
}
You are supposed to use this by writing PaymentProvider.AllPaymentProviders["key"].pay(). The idea is that the functions using this class don't need to know about how the underlying payment provider is implemented, they just need to know the key.
However, at the moment, if you have access to the PaymentProvider class, you also have access to the inheriting classes. Its possible to instantiate a new copy of the inheriting classes, and make use of them in an unexpected way. I want to encapsulate the inheriting classes so that only the abstract PaymentProvider knows about them.
How should I do this? Different protection levels like protected don't work here - In Java, protected means that only other classes in the namespace can use that class, but in C# it means something else.
Do I have the right idea here? Or should I use a different method?
A couple of options spring to mind:
Put this in a separate assembly from the client code, and make the implementations abstract
Put the implementations inside the PaymentProvider class as private nested classes. You can still separate the source code by making PaymentProvider a partial class - use one source file per implementation
The first option is likely to be the cleanest if you don't mind separating the clients from the implementation in terms of assemblies.
Note that both of these are still valid options after the change proposed by Jamiec's answer - the "visibility" part is somewhat orthogonal to the inheritance part.
(As an aside, I hope the method is really called Pay() rather than pay() :)
Your inheritance heirachy is a bit wonky, I would be tempted to do it a similar but crucially different way.
public interface IPaymentProvider
{
void Pay()
}
// Implementations of IPaymentProvider for PaypalPaymentProvider & WorldpayPaymentProvider
public static class PaymentHelper
{
private static var providers = Dictionary<String,IPaymentProvider>
{
{"paypal",new PaymentProviderPaypal()},
{"worldpay",new PaymentProviderWorldpay()}
}
public static void Pay(string provider)
{
if(!providers.Containskey(provider))
throw new InvalidOperationException("Invalid provider: " + provider);
providers[provider].Pay();
}
}
Then the usage would be something like PaymentHelper.Pay("paypal").
Obviously if there is more data to provide to the Pay method this can be added to both the interface, and the helper. for example:
public interface IPaymentProvider
{
void Pay(double amount);
}
public static void Pay(string provider, double amount)
{
if(!providers.Containskey(provider))
throw new InvalidOperationException("Invalid provider: " + provider);
providers[provider].Pay(amount);
}

Problem with types only being known at run-time causing DI pains

I'll explain my problem with an example.
I have an AnimalService, allowing me to increase the amount of show time the favourite animal gets for a specific zoo:
public sealed class AnimalService<TZoo> : IAnimalService<TZoo> where TZoo : IZoo
{
private readonly IFavouriteAnimalResolver<TZoo> favouriteAnimalResolver;
private readonly IAnimalShowTimeService animalShowTimeService;
public AnimalService(
IFavouriteAnimalResolver<TZoo> favouriteAnimalResolver,
IAnimalShowTimeService animalShowTimeService)
{
this.favouriteAnimalResolver = favouriteAnimalResolver;
this.animalShowTimeService = animalShowTimeService;
}
public void IncreaseShowTimeForFavouriteAnimal(TZoo zoo)
{
var favouriteAnimal = favouriteAnimalResolver.GetFavouriteAnimal(zoo);
animalShowTimeService.IncreaseShowTimeForAnimal(favouriteAnimal);
}
}
The AnimalService uses a resolver to get the favourite animal for TZoo, and then it calls an instance of IAnimalShowTimeService to increase the amount of show time the favourite animal will get. Below is the definition of the IFavouriteAnimalResolver interface and implementation of it that allows me to resolve the favourite animal for LondonZoo:
public interface IFavouriteAnimalResolver<TZoo> where TZoo : IZoo
{
IAnimal GetFavouriteAnimal(TZoo londonZoo);
}
public class LondonZooFavouriteAnimalResolver : IFavouriteAnimalResolver<LondonZoo>
{
public IAnimal GetFavouriteAnimal(LondonZoo londonZoo)
{
return new Lion();
}
}
Oki, so all good so far. Now for the complication. I would like to perform some animal specific logic once the IncreaseShowTimeForFavouriteAnimal is run. So my base AnimalShowTimeService stub looks like this:
public class AnimalShowTimeService : IAnimalShowTimeService
{
public void IncreaseShowTimeForAnimal(IAnimal animal)
{
// Update the show time for the animal
// Now call out to the AnimalUpdatedService<> instance to do any logic required for the animal
}
}
I would like to be able to call an update service that will get resolved via structuremap for the specific animal type, so I can run some update logic related to that specific type of animal. I have the following animalupdated interfaces for this purpose:
public interface IAnimalUpdatedService<T> where T : IAnimal
{
void LogTheUpdate(T animal);
}
public class DefaultAnimalUpdatedService<T> : IAnimalUpdatedService, IAnimalUpdatedService<T> where T : IAnimal
{
public void LogTheUpdate(T animal)
{
}
}
public class LionUpdatedService : IAnimalUpdatedService<Lion>
{
public void LogTheUpdate(Lion animal)
{
Console.WriteLine("The lion was updated");
}
}
As you can see, I have a DefaultAnimalUpdatedService which I want to be used when no specific update service was registered for an animal. I also have a LionUpdatedService which I would like to use every time a Lion's show time was increased for a zoo.
My problem is that because the favourite animal for a zoo can be any animal, the IFavouriteAnimalResolver returns an IAnimal type back and not a concrete. So I am not sure how I can use structuremap within IncreaseShowTimeForAnimal to get the LionUpdatedService service when a Lion's show time has been updated. I have played around with following code, but this won't work because I don't know the concrete at design time:
public class AnimalShowTimeService : IAnimalShowTimeService
{
public void IncreaseShowTimeForAnimal(IAnimal animal)
{
// Update the show time for the animal
var animalUpdatedService = ObjectFactory.ForGenericType(typeof(IAnimalUpdatedService<>))
.WithParameters(animal.GetType())
.GetInstanceAs<IDONTKNOWTHECONCRETE>();
animalUpdatedService.LogTheUpdate(animal);
}
}
I hope this all is clear. :)
I am not very well versed in StrutureMap, so would appreciate if anyone knows of an elegant way to approach this problem.
I have zipped up a test project I created using the above described code. You can download it here if you want to have a quick environment to fool around in:
[removed this link - no longer needed]
EDIT:
This is just a test project I created to illustrate the problem I am currently having in a much larger and more complex project. Unfortunately I can't redesign the entire architecture of the project to find a better design more geared towards this solution as I simply don't have the time. Being able to get the structuremap call simply return the correct concrete based on requirements above would be my immediate win. Learning about a better design to ensure things like this don't happen to me again would be a secondary win.
Thanks people :)
A few points:
a) Following the principle of "Tell, don't ask", it is not the AnimalShowTimeService's reposibility to resolve the type. Push the Animal to another object to make the choice.
b) Hardcoding references to ObjectFactory inside your domain is a bad design. The purpose of a DI container is to decouple your objects, not move the coupling somewhere else (StructureMap in this case).
Edit:
With regards to a) don't solve it in a polymorphic manner. You don't need generics to share behaviour, and inheritance hierachies only increase coupling. If you really do need to go down this path, I think implementing your own Convention might be what you're looking for. Or you could name every instance of IAmimal, and resolve the service with ObjectFactory.GetInstance(animal.GetType().ToString()), but that is clearly not ideal.
I think the point is however, that you're doing this as an exercise for DI & DI containers (I think), and if you can't get your design to fit, maybe you need to scrap it and start again, rather than trying to force a square peg into a round hole.
Oki, I have got a solution for my problem. Namely, the Visitor pattern. :-)
Quick reference: The Visitor Pattern
So I define a show time updated visitor, which can contain logic for each specific animal type:
public interface IShowTimeUpdatedVisitor
{
void Visit(Lion lion);
void Visit(Elephant lion);
void Visit(IAnimal animal);
}
public class ShowTimeUpdatedVisitor : IShowTimeUpdatedVisitor
{
public void Visit(Lion lion)
{
//do stuff with a lion
}
public void Visit(Elephant elephant)
{
//do stuff with an elephant
}
public void Visit(IAnimal animal)
{
// this will be the default which will be hit if no Visit method for the concrete exists
}
}
Then I have made modifications to the IAnimal interface to allow each implementation to call the correct method against ShowTimeUpdatedVisitor:
public interface IAnimal
{
void ShowTimeUpdated(IShowTimeUpdatedVisitor updatedVisitor);
}
public class Lion : IAnimal
{
public void ShowTimeUpdated(IShowTimeUpdatedVisitor updatedVisitor)
{
updatedVisitor.Visit(this);
}
}
Now, I can implement my AnimalShowTime service like this:
public class AnimalShowTimeService : IAnimalShowTimeService
{
readonly IShowTimeUpdatedVisitor showTimeUpdatedVisitor;
public AnimalShowTimeService(
IShowTimeUpdatedVisitor showTimeUpdatedVisitor)
{
this.showTimeUpdatedVisitor = showTimeUpdatedVisitor;
}
public void IncreaseShowTimeForAnimal(IAnimal animal)
{
animal.ShowTimeUpdated(showTimeUpdatedVisitor);
}
}
So in the end I didn't have to do any messy StructureMap code. :)
Hope this helps someone else.

Categories

Resources