Refactoring with generics - c#

Let's assume, that we have the following classes:
class ViewModelA
{
private ProxyA proxy;
public ViewModelA(DataA data)
{
proxy = new ProxyA(data);
}
public void DoSth()
{
proxy.DoSth();
}
public ProxyA Proxy
{
get
{
return proxy;
}
}
}
class ViewModelB
{
private ProxyB proxy;
public ViewModelB(DataB data)
{
proxy = new ProxyB(data);
}
public void DoSth()
{
proxy.DoSth();
}
public ProxyB Proxy
{
get
{
return proxy;
}
}
}
...
All of these classes are actually a lot longer, but also similar in the same degree.
Is there a (nice) way of converting them all to one generic class? The core problem is the line:
proxy = new ProxyA(data);
because C# disallows calling parametrized ctors on generic class specializations (in terms of T).

You can solve this by passing in a preconstructed ProxyA or ProxyB object.
One way of doing it is through inheritance, constructing the object just before calling the base constructor:
class ViewModel<TProxy, TData>
{
private TProxy proxy;
public ViewModel(TProxy proxy)
{
this.proxy = proxy;
}
public void DoSth()
{
proxy.DoSth();
}
public TProxy Proxy
{
get
{
return proxy;
}
}
}
class ViewModelA : ViewModel<ProxyA, DataA>
{
public ViewModelA(DataA data) : base(new ProxyA(data))
{
}
}
I've assumed here that DataA and DataB occurs somewhere in method signatures that you have omitted. If not, you can leave out the TData generic type parameter.
Reflection is always an option, but it is best avoided if a solution like this is acceptable. If you want to avoid having to create a new type for a different TProxy and TData, you could add a second constructor instead:
ViewModel(TData data, Func<TData, TProxy> factory) : this(factory(data))
{
}
Used as such:
new ViewModel<ProxyA, DataA>(new DataA(), data => new ProxyA(data));
I'm not sure if that makes sense to do in your application however.

If you know the type (and using generics you would), you can call Activator.CreateInstance to create an instance of that type using any constructor you want.
proxy = Activator.CreateInstance(typeof(TProxy), new[]{data});
While this will solve your direct problem, you could also think about a design where ViewModelA does not know about DataA and instead gets passed a ProxyA. That would solve all your problems without fancy reflection.

As you noted, it is not possible to do this with parameterised constructors, without using reflection. However, one possible variation on this theme:
public interface IDataProxy<T>
{
T Data { get; set; }
}
public class ViewModel<TProxy, TData>
where TProxy : class, new, IDataProxy<TData>
{
public TProxy Proxy { get; private set; }
public ViewModel(TData data)
{
Proxy = new TProxy { Data = data };
}
}

public interface IProxy
{
void DoSth();
}
public class ProxyA : IProxy
{
public ProxyA(DataA dataA)
{
}
public void DoSth()
{ }
}
public class ProxyB : IProxy
{
public ProxyB(DataB dataA)
{
}
public void DoSth()
{
}
}
public class ViewModel<T> where T : IProxy
{
private readonly IProxy _proxy;
public ViewModel(T proxy)
{
_proxy = proxy;
}
public void DoSth()
{
_proxy.DoSth();
}
}
var vm = new ViewModel<ProxyA>(new ProxyA(new DataA()));
vm.DoSth();

public interface IDoSomething
{
void DoSth();
}
class ViewModel<T> where T : IDoSomething
{
private T proxy;
public ViewModel()
{
proxy = Activator.CreateInstance<T>();
}
//public ViewModel(T data)
//{
// proxy = data;
//}
public void DoSth()
{
proxy.DoSth();
}
public T Proxy
{
get
{
return proxy;
}
}
}

Related

How to instantiate a class as the interface that it derives from with constrained generic type parameter

There's the following interface which defines a packet.
public interface IPacket
{
int Size { get; }
}
There are two implementations, each with its own additional property.
public class FooPacket : IPacket
{
public int Size => 10;
public string FooProperty { get; set; }
}
public class BarPacket : IPacket
{
public int Size => 20;
public string BarProperty { get; set; }
}
The above is library code I have no control over. I want to create a handler for packets
public interface IPacketHandler<T> where T : IPacket
{
void HandlePacket(T packet) ;
}
and create two implementations for the concrete packets.
public class FooPacketHandler : IPacketHandler<FooPacket>
{
public void HandlePacket(FooPacket packet) { /* some logic that accesses FooProperty */ }
}
public class BarPacketHandler : IPacketHandler<BarPacket>
{
public void HandlePacket(BarPacket packet) { /* some logic that accesses BarProperty */ }
}
I'd like to inject a list of packet handlers into a class that manages packet handling so that it can be extended in the future with additional packet handlers.
public class PacketHandlerManager
{
public PacketHandlerManager(IEnumerable<IPacketHandler<IPacket>> packetHandlers)
{
}
}
The trouble I'm having is when creating the injected parameter. I cannot do
var packetHandlers = new List<IPacketHandler<IPacket>>
{
new FooPacketHandler(),
new BarPacketHandler()
};
because I cannot create an instance like so:
IPacketHandler<IPacket> packetHandler = new FooPacketHandler();
I get the error Cannot implicitly convert type 'FooPacketHandler' to 'IPacketHandler<IPacket>. An explicit conversion exists (are you missing a cast?)
I had a look at a similar question: Casting generic type with interface constraint. In that question, OP didn't show the members of the interface, only the definition of it from a generics point of view. From what I can see, if my interface didn't use the generic type parameter as an input, I could make it covariant using the out keyword, but that doesn't apply here.
How do I achieve making manager adhere to the open-closed principle? Is my only recourse changing the interface definition to
public interface IPacketHandler
{
void HandlePacket(IPacket packet);
}
and then casting to a particular packet in the implementation?
The core of the issue is that ultimately you would call your handler passing a concrete packet (of a concrete type) to it as an argument, even though you hide the argument behind IPacket.
Somehow then, trying to call the HandlePacket( FooPacket ) with BarPacket argument would have to fail, the only question is when/where it fails.
As you already noticed, introducing the generic parameter to the packet handler makes it fail in the compile time and there is no easy workaround over it.
Your idea to drop the generic parameter, i.e. to have
public interface IPacketHandler
{
void HandlePacket(IPacket packet);
}
is a possible solution. It however pushes the possible failure to the runtime, where you now have to check if a handler is called with inappropriate argument.
What you could also do is to make this runtime check more explicit by introducing a contract for it:
public interface IPacketHandler
{
bool CanHandlePacket(IPacket packet);
void HandlePacket(IPacket packet);
}
This makes it cleaner for the consumer to safely call HandlePacket - assuming they get a positive result from calling CanHandlePacket before.
For example, a possible naive loop over a list of packets and calling your handlers would become
foreach ( var packet in _packets )
foreach ( var handler in _handlers )
if ( handler.CanHandlePacket(packet) )
handler.HandlePacket(packet);
You can solve this with a little bit of reflection.
Firstly, for convenience (and to help slightly with type-safety), introduce a "Tag" interface which all your IPacketHandler<T> interfaces will implement:
public interface IPacketHandlerTag // "Tag" interface.
{
}
This is not really necessary, but it means you can use IEnumerable<IPacketHandlerTag> instead of IEnumerable<object> later on, which does make things a little more obvious.
Then your IPacketHandler<T> interface becomes:
public interface IPacketHandler<in T> : IPacketHandlerTag where T : IPacket
{
void HandlePacket(T packet);
}
Now you can write a PacketHandlerManager that uses reflection to pick out the method to use to handle a packet, and add it to a dictionary like so:
public class PacketHandlerManager
{
public PacketHandlerManager(IEnumerable<IPacketHandlerTag> packetHandlers)
{
foreach (var packetHandler in packetHandlers)
{
bool appropriateMethodFound = false;
var handlerType = packetHandler.GetType();
var allMethods = handlerType.GetMethods(BindingFlags.Public | BindingFlags.Instance);
foreach (var method in allMethods.Where(m => m.Name == "HandlePacket"))
{
var args = method.GetParameters();
if (args.Length == 1 && typeof(IPacket).IsAssignableFrom(args[0].ParameterType))
{
_handlers.Add(args[0].ParameterType, item => method.Invoke(packetHandler, new object[]{item}));
appropriateMethodFound = true;
}
}
if (!appropriateMethodFound)
throw new InvalidOperationException("No appropriate HandlePacket() method found for type " + handlerType.FullName);
}
}
public void HandlePacket(IPacket packet)
{
if (_handlers.TryGetValue(packet.GetType(), out var handler))
{
handler(packet);
}
else
{
Console.WriteLine("No handler found for packet type " + packet.GetType().FullName);
}
}
readonly Dictionary<Type, Action<IPacket>> _handlers = new Dictionary<Type, Action<IPacket>>();
}
If a packet handler passed to the PacketHandlerManager constructor does not implement a method called HandlePacket with a single argument that is assignable from IPacket, it will throw an InvalidOperationException.
For example, attempting to use an instance of the following class would cause the constructor to throw:
public class BadPacketHandler: IPacketHandlerTag
{
public void HandlePacket(string packet)
{
Console.WriteLine("Handling string");
}
}
Now you can call use it thusly:
var packetHandlers = new List<IPacketHandlerTag>
{
new FooPacketHandler(),
new BarPacketHandler()
};
var manager = new PacketHandlerManager(packetHandlers);
var foo = new FooPacket();
var bar = new BarPacket();
var baz = new BazPacket();
manager.HandlePacket(foo);
manager.HandlePacket(bar);
manager.HandlePacket(baz);
Putting it all together into a compilable console app:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace ConsoleApp1
{
public interface IPacket
{
int Size { get; }
}
public class FooPacket : IPacket
{
public int Size => 10;
public string FooProperty { get; set; }
}
public class BarPacket : IPacket
{
public int Size => 20;
public string BarProperty { get; set; }
}
public class BazPacket : IPacket
{
public int Size => 20;
public string BazProperty { get; set; }
}
public interface IPacketHandlerTag // "Tag" interface.
{
}
public interface IPacketHandler<in T> : IPacketHandlerTag where T : IPacket
{
void HandlePacket(T packet);
}
public class FooPacketHandler : IPacketHandler<FooPacket>
{
public void HandlePacket(FooPacket packet)
{
Console.WriteLine("Handling FooPacket");
}
}
public class BarPacketHandler : IPacketHandler<BarPacket>
{
public void HandlePacket(BarPacket packet)
{
Console.WriteLine("Handling BarPacket");
}
}
public class PacketHandlerManager
{
public PacketHandlerManager(IEnumerable<IPacketHandlerTag> packetHandlers)
{
foreach (var packetHandler in packetHandlers)
{
bool appropriateMethodFound = false;
var handlerType = packetHandler.GetType();
var allMethods = handlerType.GetMethods(BindingFlags.Public | BindingFlags.Instance);
foreach (var method in allMethods.Where(m => m.Name == "HandlePacket"))
{
var args = method.GetParameters();
if (args.Length == 1 && typeof(IPacket).IsAssignableFrom(args[0].ParameterType))
{
_handlers.Add(args[0].ParameterType, item => method.Invoke(packetHandler, new object[]{item}));
appropriateMethodFound = true;
}
}
if (!appropriateMethodFound)
throw new InvalidOperationException("No appropriate HandlePacket() method found for type " + handlerType.FullName);
}
}
public void HandlePacket(IPacket packet)
{
if (_handlers.TryGetValue(packet.GetType(), out var handler))
{
handler(packet);
}
else
{
Console.WriteLine("No handler found for packet type " + packet.GetType().FullName);
}
}
readonly Dictionary<Type, Action<IPacket>> _handlers = new Dictionary<Type, Action<IPacket>>();
}
class Program
{
public static void Main()
{
var packetHandlers = new List<IPacketHandlerTag>
{
new FooPacketHandler(),
new BarPacketHandler()
};
var manager = new PacketHandlerManager(packetHandlers);
var foo = new FooPacket();
var bar = new BarPacket();
var baz = new BazPacket();
manager.HandlePacket(foo);
manager.HandlePacket(bar);
manager.HandlePacket(baz);
}
}
}
The output of this is:
Handling FooPacket
Handling BarPacket
No handler found for packet type ConsoleApp1.BazPacket
Thanks for the answers. The solution I ended up with is this, starting with the library code:
public enum PacketType
{
Foo,
Bar
}
public interface IPacket
{
PacketType Type { get; }
}
public class FooPacket : IPacket
{
public PacketType Type => PacketType.Foo;
public string FooProperty { get; }
}
public class BarPacket : IPacket
{
public PacketType Type => PacketType.Bar;
public string BarProperty { get; }
}
The above version is a better approximation of the real thing.
public interface IPacketHandler
{
void HandlePacket(IPacket packet);
}
public abstract class PacketHandler<T> : IPacketHandler where T : IPacket
{
public abstract PacketType HandlesPacketType { get; }
public void HandlePacket(IPacket packet)
{
if (packet is T concretePacket)
{
HandlePacket(concretePacket);
}
}
protected abstract void HandlePacket(T packet);
}
public class FooPacketHandler : PacketHandler<FooPacket>
{
public override PacketType HandlesPacketType => PacketType.Foo;
protected override void HandlePacket(FooPacket packet) { /* some logic that accesses FooProperty */ }
}
public class BarPacketHandler : PacketHandler<BarPacket>
{
public override PacketType HandlesPacketType => PacketType.Bar;
protected override void HandlePacket(BarPacket packet) { /* some logic that accesses BarProperty */ }
}
public class PacketHandlerManager
{
public PacketHandlerManager(Library library, IEnumerable<IPacketHandler> packetHandlers)
{
foreach (var packetHandler in packetHandlers)
{
library.Bind(packetHandler.HandlesPacketType, packetHandler.HandlePacket);
}
}
}
There's some more logic in PacketHandlerManager which I've omitted here. library dispatches packets to handlers, so I don't have to deal with that explicitly after I register handlers using the Bind method.
It's not exactly what I imagined, but it'll do.

Why do I need to declare the type?

I have the following code:
public interface IMyActionFactory
{
AbstractAction<T> CreateAction<T>(MyActionParamBase paramBase = null)
where T : MyActionParamBase;
}
public sealed class MergeActionParam : MyActionParamBase
{
}
public class MergeTest
{
private readonly IMyActionFactory _actionFactory = new DefaultMyActionFactory();
[Theory]
[PropertyData("MergeWorksData")]
public void MergeWorks(/*params here*/)
{
var param = new MergeActionParam();
// populate param here
var sut = _actionFactory.CreateAction<MergeActionParam>(param);
sut.DoAction();
}
}
I am getting an error
"..Error 10 Using the generic type 'IMyActionFactory' requires 1
type arguments..."
Why does the compiler expect a type to be passed to my IMyActionFactory, since I have declared the interface without a T? As far as the method is concerned its the only one to expect the type. Am I missing something here?
How can I make it work without redefining the interface signature?
EDIT:
Feeling a bit embarassed here, because the quick code I put down and ran seperately in a standalone online c# compiler doesnt give any compilation errors. However, going back to my original solution (tens of projects altogether) the error is still there.. Maybe has something to do with the XUnit ?..not sure
public interface IMyActionFactory
{
AbstractAction<T> CreateAction<T>(MyActionParamBase paramBase = null)
where T : MyActionParamBase;
}
public interface IAction
{
void DoAction();
}
public abstract class AbstractAction<T> : IAction
where T : MyActionParamBase
{
public void DoAction()
{
}
}
public class MyActionParamBase
{
public MyActionParamBase()
{
}
}
public sealed class MergeActionParam : MyActionParamBase
{
}
public class DefaultMyActionFactory : IMyActionFactory
{
public AbstractAction<T> CreateAction<T>(MyActionParamBase paramBase = null) where T : MyActionParamBase
{
return null;
}
}
public class MergeTest
{
private readonly IMyActionFactory _actionFactory = new DefaultMyActionFactory();
public void MergeWorks(/*params here*/)
{
var param = new MergeActionParam();
// populate param here
var sut = _actionFactory.CreateAction<MergeActionParam>(param);
sut.DoAction();
}
}

Get trait in subclass

I'm sorry if this is poorly worded or if this has been asked before but I couldn't seem to find anything related to this and I'm quite tired.
Alright, so what I'm trying to do is get the value of of my trait in a subclass for situations where I need to reference an instance of a subclass but I don't have the information about what trait it will be using. This is easier for me to explain in code so here's what I'm trying to do.
public class TraitUser<T>
{
public void DoThingWithT(T thing)
{
thing.ToString();
}
}
public class TraitInspector
{
public void DoThing()
{
// This is where I run into my issue,
// I need to be able to get the trait that
// an instance of the TraitUser class is using to continue.
TraitUser<> tUser = GetRandomTraitUser()/*Imagine this returns an instance of TraitUser with a random trait, this is where my issue comes in.*/;
}
}
If I understand youright, you need get information about generic type T in TraitUser instance in TrairInspector.
public interface IGetTraitInfo
{
Type GetTraitObjectType();
object GetTraitObject();
}
public class TraitUser<T> : IGetTraitInfo
{
private T _thing;
public void DoThingWithT(T thing)
{
_thing = thing;
}
public Type GetTraintObjectType()
{
return typeof(T);
}
public Type GetTraitObject()
{
return _thing;
}
}
public class TrairInspector
{
public void InspectTraitUser(IGetTraitInfo traitUser)
{
Type traitType = traitUser.GetTraintObjectType();
object data = traitUser.GetTraitObject();
}
}
I didn't understand completely but this might help you.
public interface ITrait
{
string DoSomething();
}
public class Trait<T> where T : ITrait, new()
{
public string DoSomething()
{
ITrait trait = new T();
return trait.DoSomething();
}
}
public class TraitUser : ITrait
{
public string DoThing()
{
return "return something";
}
}
public class TrairInspector
{
public void DoThing()
{
Trait<TraitUser> traitUser = new Trait<TraitUser>();
traitUser.DoSomething();
}
}

Proper way to inherit fields from a Base Class?

Is the following code below good enough or should something like an interface or abstract class be used?
I had some common code, but I did not see a reason for an abstract class or an interface.
Also, there is no way to tell serviceClient came from BaseTask without exploring or hovering over it. Is there something in each Task1 and Task2 to indicate this?
public class BaseTask
{
private string configValue1 = "abc";
private string configValue2 = "def";
public ServiceClient serviceClient = new ServiceClient(configValue1,configValue2);
}
public class Task1 : BaseTask
{
public void RunTask()
{
serviceClient.RunTask1();
}
}
public class Task2 : BaseTask
{
public void RunTask()
{
serviceClient.RunTask2();
}
}
public class BaseTask
{
private readonly string configValue1 = "abc";
private readonly string configValue2 = "def";
private readonly ServiceClient serviceClient = new ServiceClient(configValue1,configValue2);
public ServiceClient ServiceClient { get{ return serviceClient;} }
}
public class Task1 : BaseTask
{
public void RunTask()
{
ServiceClient.RunTask1();
}
}
public class Task2 : BaseTask
{
public void RunTask()
{
ServiceClient.RunTask2();
}
}
Architectually I would just make serviceClient a read-only property. Stylistically I would follow proper casing conventions for .NET:
private ServiceClient serviceClient = new ServiceClient(configValue1,configValue2);
public ServiceClient ServiceClient
{
get { return serviceClient; }
}
It may also make sense to make RunTask virtual since the implementations you show are the same (and it allows you to override it in other implementations if necessary):
public virtual void RunTask()
{
serviceClient.RunTask1();
}
If it doesn't make sense to create an instance of BaseTask on its own then make it abstract to prevent anyone from doing so. This also make your intention clear (ie that BaseTask should only be derived from).
I'd also recommend not making variables public. Instead hide them behind properties.
You don;t currently have any properties. If you need your specific value, try the below.
public class BaseTask
{
private string _configValue1 = "abc";
private string _configValue2 = "def";
private ServiceClient _serviceClient1 = new ServiceClient(configValue1,configValue2);
Public ServiceClient ServiceClient1
{
get
{
return _serviceClient1;
}
set
{
serviceClient1 = value;
}
}
Public string ConfigValue1
{
get
{
return _configValue1;
}
set
{
_configValue1= value;
}
}
Public string ConfigValue2
{
get
{
return _configValue2;
}
set
{
_configValue2 = value;
}
}

Add object which does not implement interface, but meets all qualifications, to a list expecting interface

I have the following:
List<IReport> myList = new List<IReport>();
Report myReport = TheirApi.GetReport();
myReport meets all the qualifications of IReport, but cannot implement IReport because I do not have access to the source of TheirApi. Casting to type IReport obviously results in null, and I read that I cannot cast an anonymous type to an interface.
Do I have any options here?
A wrapper class was just what the doctor ordered:
ReportServices.GetAllCustomReports().ToList().ForEach(customReport => _customReports.Add(new ReportWrapper(customReport)));
public class ReportWrapper : IReport
{
private Report inner;
public int ID
{
get { return inner.ID; }
set { inner.ID = value; }
}
public string Name
{
get { return inner.Name; }
set { inner.Name = value; }
}
public ReportWrapper(Report obj)
{
inner = obj;
}
}
You will need to wrap this object inside another one that implements the interface, and then you will need to implement it calling the inner object's properties and methods.
For example:
public class ReportWrapper : IReport
{
MyObjectIsLikeReport inner;
public ReportWrapper(MyObjectIsLikeReport obj) {
this.inner = obj;
}
public void ReportMethod(int value) {
this.inner.ReportMethod(value);
}
public int SomeProperty {
get { return this.inner.SomeProperty; }
set { this.inner.SomeProperty = value; }
}
}
To use it, you can do this:
List<IReport> myList = new List<IReport>();
MyObjectIsLikeReport myReport = TheirApi.GetReport();
myList.Add(new ReportWrapper(myReport));
Consider Adapter Design Pattern.
Definition: Convert the interface of a class into another interface
clients expect. Adapter lets classes work together that couldn't
otherwise because of incompatible interfaces.
good reference: http://www.dofactory.com/Patterns/PatternAdapter.aspx
interface IReport
{
void DoSomething();
}
class ReportApdapter : IReport
{
private readonly Report _report;
public ReportApdapter(Report report)
{
_report = report;
}
public void DoSomething()
{
_report.DoSomething();
}
}
class Report
{
public void DoSomething()
{
}
}
//You can use like this.
IReport report = new ReportApdapter(TheirApi.GetReport());

Categories

Resources