I've written a method:
class CopyableFloatCommand : FloatCommand
{
public CopyableFloatCommand DeepCopy(LocationHeaderDTO locHeader, string commandId,
List<FloatProductDetailsDTO> recountProuducts)
{
var newCommand = (CopyableFloatCommand)MemberwiseClone();
newCommand.Location = locHeader ?? newCommand.Location;
newCommand.CommandId = commandId ?? newCommand.CommandId;
newCommand.RecountProducts = recountProuducts ?? newCommand.RecountProducts;
return newCommand;
}
}
And am then calling it via:
_tCheckinCommand = _pTCommand.DeepCopy(stagingLocHeadDto, SCICommand,
new List<FloatProductDetailsDTO>(_pTCommand.MoveProducts));
In order to deepcopy an object of type FloatCommand.
As the MemberwiseClone() is a protected method, it's got to be called the way you see above - one cannot parse in a FloatCommand type in the method parameter and call it via fc.MemberwiseClone(), for example. As my method ought to work on a FloatCommand type, I've created a new nested class CopyableFloatCommand which inherits from FloatCommand. DeepCopy method then shallow clones the FloatCommand, casts to the child type and changes some properties as/when needed.
Creating a new class specifically for this purpose seems a bit clunky and I didnt' see a more obvious way of writing it at the time. In terms of lines-of-code, would there be a simpler way of employing a deepcopy such as the above? What about if another class, UserCommand, attempted to deepcopy a User object? UserComand would be a sibling to FloatCommand such that they both inherit from Command. The method would have different parameters parsed for the different types (although I can just remove the parameters altogether and use the instance variables if need be) as the different sub-types have slightly different properties.
In light of this is there a more generic method of writing the DeepCopy method, to be available for access for all the Command types in order to avoid some code duplication, given the above constraints?
Thanks!
I think you're suspecting that the responsibility of cloning the object and mutate its state after it is cloned should be separated - since you're facing with the similar task again (i mean UserCommand).
I would do the following in this situation:
Create a mutation interface:
public interface ICopyCommandMutation
{
void Mutate(Command target);
}
For the sake of extensability i would create the default muate implementation:
public class NoMutation : ICopyCommandMutation
{
public void Mutate(Command target) {}
}
Create the CopyableCommand class and move the DeepCopy() method there (you should also inherit FloatCommand from CopyableCommand):
public CopyableCommand : Command
{
public CopyableCommand DeepCopy(ICopyCommandMutation commandMutation = null)
{
var newCommand = (CopyableCommand)MemberwiseClone();
if (commandMutation == null) commandMutation = new NoMutation();
commandMutation.Mutate(newCommand);
return newCommand;
}
}
Now all the CopyableCommand inheritors can be copied with 'mutations' - you just need to implement the class. For example the FloatCommand 'mutations' from your question:
public class ChangeLocationRecountProducts : ICopyCommandMutation
{
// these fields should be initialized some way (constructor or getter/setters - you decide
LocationHeaderDTO locHeader;
string commandId;
List<FloatProductDetailsDTO> recountProducts;
public void Mutate(Command floatCommand)
{
var fc = floatCommand as FloatCommand;
if (fc == null) { /* handle problems here */ }
fc.Location = locHeader ?? fc.Location;
fc.CommandId = commandId ?? fc.CommandId;
fc.RecountProducts = recountProuducts ?? fc.RecountProducts;
}
}
Here is the usage:
var clrp = new ChangeLocationRecountProducts();
// ... setting up clrp
_tCheckinCommand = _pTCommand.DeepCopy(clrp);
Now if you need to 'mutate' the UserCommand - you can do the separate mutation class for it and keep the mutation logic there. The ability to make different mutations in different sutations (just by defining the separate mutation classes) comes for free.
The only problem i can see here - is that you probably cannot create CopyableCommand and inherit other commands from it (3rd party library?). The solution would be to use Castle dynamic proxy.
I haven't used the Automapper but i suspect that it is doing something similar.
The solution is not 'lines-of-code optimal' - but you would benefit from it if you have to mutate large number of command classes when copying instances.
Related
I have a (growing) list of Data-Generators. The generator that I need is created by a factory class. The generators all implement a common Interface, which includes among other things a static string name.
What I would like to do: Call the factory.Create method with a string parameter for the above mentioned name. The create method finds the generator with this name and returns a new instance of said generator.
Bonus in my opinion of this way to do it: I only have to add new generator classes without having to edit the factory.
Question:
Is this a good way to handle this problem?
How can I find all generators? Reflection over every implementation of the interface/every member of the namespace (unique for the generators + their interface)?
Is it correct to call this way of working a factory, or is this some different pattern?
In the end I would call the factory like this (simplified):
//Caller
public DataModel GetData2()
{
var generator = new DataFactory().Create("Gen.2");
return generator.GetData();
}
//Factory
public class DataFactory
{
public AbstractDataGenerator Create(string type)
{
//Here the magic happens to find all implementations of IDataGenerator
var allGenerators = GetImplementations();
var generator = allGenerators.FirstOrDefault(f => f.name == type);
if (generator != null)
return (AbstractDataGenerator)Activator.CreateInstance(generator);
else
return null;
}
}
//Interface
public abstract class AbstractDataGenerator
{
public static string name;
public abstract DataModel GetData();
}
//Data-Generators
public class DataGen1 : AbstractDataGenerator
{
public static string name = "Gen.1";
public DataModel GetData()
{
return new DataModel("1");
}
}
public class DataGen2 : AbstractDataGenerator
{
public static string name = "Gen.2";
public DataModel GetData()
{
return new DataModel("2");
}
}
Should the magic GetImplementations() in the factory be done via Reflection or somehow different? Should I use a completely different approach?
Since answers refer to IoC and DI: This project uses NInject already, so it would be available.
Switched from interface to abstract class.
Is this a good way to handle this problem?
Having a factory to get an instance of the logic class you need by some key - I believe it is a good way. It is a pattern that I use a lot myself. About the way you have your key - I'd prefer to not have it as a static member (regardless to the fact that interfaces can't have static members) but just as a property and to add a base class to the IDataGenerator. That base class will have a constructor that will get the name - That way each new DataGenerator you create will have to set it and you wont forget.
About having the name as a string - I personally prefer having it "strongly typed". What I mean is that if I pass Gen . 2 instead of Gen.2 with strings I will discover this problem only in runtime. Possible other ways (if you want, because a simple string is fine too - a matter of taste):
Replace strings with an enum
Have a static class with static readonly strings for all your values - then in your code use those values. You get the benifits of the intellisense and of not getting the string wrong but better than enum - you can just still pass strings that are not in the "list" so you can add new ones as add-ons.
Have a RequestGenerator object, with each Generator being IDataGenerator<TGeneratorRequest>. This might be an overkill but if you have also extra information you need for the creating of a DataGenerator which differs between them then consider it .
How can I find all generators? Reflection over every implementation of the interface/every member of the namespace (unique for the generators + their interface)?
Yes, reflection can be a good way to do so. However, I would suggest to read into Dependency Injection and IoC Containers like Castle Windsor for example. There are things out there that already implement it for you, so why to re-invent the wheel :)
DI is a life changer concept in my opinion
Is it correct to call this way of working a factory, or is this some different pattern?
Yap. It is a Factory
Should the magic GetImplementations() in the factory be done via Reflection or somehow different?
See answer for question 2
This is where constructor injection can REALLY shine. Look into dependency injection tools and employ one! It also checks your "Bonus" request.
Here's what your factory might look like with constructor injection:
public class DataFactory
{
private Dictionary<string, IDataGenerator> generators;
public DataFactory(IDataGenerator[] generatorReferences)
{
this.generators = generatorReferences
.ToDictionary(k => k.name, v => v);
}
public IDataGenerator Create(string type)
{
IDataGenerator generator = null;
this.generators.TryGetValue(type, out generator);
return generator;
}
}
Most DI software has the capability to automatically scan assemblies for implementations of a certain type (e.g. IDataGenerator) and register those with itself, when it constructs an instance of your DataFactory it'll automatically include them.
FYI: the verbose preamble is to help explain why I am using Activator.CreateInstance. I have a number of entities (objects corresponding to database column information) that are "contained" in multiple databases, each of which has a different table/column setup. So I am able to retrieve an entity from each database, but the way I retrieve it is different per database. The database type is not known till runtime and could vary throughout execution. I have created the following setup:
First define the query operations each entity should support and each entity reader should support these operations.
public abstract class Operations<T> {
public delegate T findDelegate(int id);
public findDelegate find;
}
// there are many of these N=1,2,..., but here is one
// use abstract class since implementation of queries should be done by handlers
public class EntityNReader : Operations<EntityN> {
public Reader();
}
Define an interface for "Handler" classes, i.e. these classes implement the query operations listed above.
public interface IHandler<T> {
public string find(int id);
}
// there are many of these N,M=1,2..., but here is one
// use of interface is to force handlers to implement all query types
public class EntityNHandlerForDbTypeM : IHandler<EntityN> {
public string find(int id) {/*whatever*/}
}
This allows the developers to create a single class for handling EntityN query operations for DbTypeM. Now, create a Database class that contains the reader objects and binds the handler methods to the reader delegates.
public class Database {
// there are many of these, but here is one
public EntityNReader EntitiesN;
public Database(string dbType) {
// this is called for each EntityNReader
bindHandlers<Reader, TypeN>(MyReader, dbType);
// ...
// nullreferenceexception
EntitiesN.find(0);
}
// this is a factory that also performs late binding
private void bindHandlers<T,K>(T reader, string dbTypeM)
where T: Operations<K>, new()
{
// create instance of EntityNReader
r = (T)Activator.CreateInstance(typeof(T));
// r != null
// create instance of handler
IHandler<K> h = (IHandler<K>)(Activator.CreateInstance(
Type.GetType("namespace.to.EntityNHandlerForDbTypeM"),
new object[] { this }
));
// bind delegates
r.find = h.find;
}
}
As you can see in Databases constructor, the way the code is written now, I get a NullReferenceException even though instance r of EntityNReader is created and (verified to be) not null.
However, if I instantiate EntitiesN where it is declared in Database instead of within bindHandlers, the code compiles and everything works. The reason I don't just do this is that (subsequently) I would like to conditionally create readers/handlers inside of bindHandlers at the time the Database class is instantiated.
What is happening here? Link to actual code if necessary.
P.S. I am relatively new to programming, so I am open to hearing how an experience developer might design this component (especially if I am heading down the wrong path).
I realize your code was just samples, but I spotted this right off the bat...
if (supports[typeof(Entity1).Name]) { bindHandlers<Entity1Reader, Entity1>(Entities1, CamaDbType); }
if (supports[typeof(Entity2).Name]) { bindHandlers<Entity1Reader, Entity1>(Entities1, CamaDbType); }
Is it possible that you have a simple copy/paste mistake? Notice that Entities1 is passed in for both bindHandlers calls.
I have a series of classes which initialize themselves when created based on using reflection to read a custom attribute on each property/field. The logic for all that is contained in an Initialize() method which they all call, which exists on the base class they inherit from.
I want to add usages of Lazy<T> to these classes, but I don't want to specify the function(s) in the constructor for each class, because they are "thin" constructors and the heavy lifting is in Initialize(). Conversely, I want to keep type-safety and such so I can't just provide a string of the code to use to initialize the Lazy<T>. The problem is that any usage which refers to the specific properties of the object can't be used in a static context.
Specifically, this is what I want my code to look like in an ideal world:
public class Data : Base
{
public Data(int ID) { Initalize(ID); }
[DataAttr("catId")] // This tells reflection how to initialize this field.
private int categoryID;
[LazyDataAttr((Data d) => new Category(d.categoryID))] // This would tell reflection how to create the Lazy<T> signature
private Lazy<Category> _category;
public Category Category { get { return _category.Value; } }
}
public abstract class Base
{
protected void Initalize(int ID)
{
// Use reflection to look up `ID` and populate all the fields correctly.
// This is where `categoryID` gets its initial value.
// *** This is where _category should be assigned the correct function to use ***
}
}
I would then access this the same way I would if Category were an automatic property (or an explicitly lazy loaded one with an _category == null check)
var data = new Data();
var cat = data.Category;
Is there any way I can pass the type information so that the compiler can check that new category(d.categoryID) is a valid function? It doesn't have to be via an Attribute, but it needs to be something I can see via Reflection and plug in to anything that has a Lazy<T> signature.
As an alternative, I will accept a way to do
private Lazy<Category> _category = (Data d) => new Category(d.categoryID);
This could either avoid reflection altogether, or use it to transform from this form to a form that Lazy<T> can handle.
I ended up using a solution inspired by #Servy's suggestion to get this working. The base class's Initialize() method now ends with:
protected void Initialize()
{
// Rest of code...
InitializeLazyVars();
/* We need do nothing here because instantiating the class object already set up default values. */
foreach (var fi in GetLazyFields())
{
if (fi.GetValue(this) == null)
throw new NotImplementedException("No initialization found for Lazy<T> " + fi.Name + " in class " + this.GetType());
}
}
InitializeLazyVars() is a virtual method that does nothing in the base class, but will need to be overridden in the child classes. If someone introduces a new Lazy<T> and doesn't add it to that method, we'll generate an exception any time we try to initialize the class, which means we'll catch it quickly. And there's only one place they need to be added, no matter how many constructors there are.
I'm working on bettering my strategy of working with classes and objects.
What is the best way of passing an object down a through a chain of specific classes to keep the code organized.
example: working with a ZedGraph object (note) this may not be the best example but it will get the idea across.
class Graphhandler
{
private ZedGraphControl ZGC;
private SubGraphController PortionofGraph;
public class GraphHandler(ZedGraphControl _ZGC)
{
ZGC = _ZGC;
initializeGraph();
}
private void initializeGraph()
{
// notice I am putting the ZGC Object into another class
// and likely that ZGC object will go into another class
PortionofGraph = new SubGraphController(ZGC);
}
}
class SubGraphController
{
private ZedGraphControl ZGC;
private DeeperSubGraphController PortionofGraph;
public class SubGraphController(ZedGraphControl _ZGC)
{
ZGC = _ZGC;
initializeSubGraph();
}
private void initializeSubGraph()
{
PortionofGraph = new DeeperSubGraphController(ZGC);
// is there a better way?
}
}
Is there a better way of passing a yop level object down through all these calls to manipulate the data?
Normally, the answer is to pass fully-formed dependencies into your objects. For example:
public GraphHandler(SubGraphController portionOfGraph) {
this.portionOfGraph = portionOfGraph;
}
public SubGraphController(DeeperSubGraphController portionOfGraph) {
this.portionOfGraph = portionOfGraph;
}
...
var zedGraphControl = new ZedGraphControl();
var deeperSubGraphController = new DeeperSubGraphController(zedGraphControl);
var subGraphController = new SubGraphController(deeperSubGraphController);
var graphHandler = new GraphHandler(subGraphController);
Rather than constructing the DeeperSubGraphController directly in you subgraph controller. Nowadays, you usually orchestrate all this using a dependency injection framework.
(See also: Dependency Injection Myth: Reference Passing)
You can take a look at Inversion Of Control (often abbrieviated IoC).
It's basically a super object that lets you access other objects whenever and wherever you need them.
You could try using inheritance in this scenario.
How will the different controllers control the graph. Generally, objects are passed around the way you have done that -- as method arguments. If an object requires/uses another object (as the contollers control the graphs in your case) across different methods then they are declared to be members of that referring object, as you have done. If they are required for a single method they are passed to the object's specific method as parameters.
If there is a more complex scheme of how the control the graphs in a specific order, you might want to take a look at the chain of responsibility pattern.
The System.Windows.Documents namespace includes a number of classes with an Inlines property of type InlineCollection. For example, the Paragraph, Bold and Hyperlink classes all have this property.
Each of these classes is decorated with ContentPropertyAttribute ...
[ContentPropertyAttribute("Inlines")]
public class Paragraph : Block
... which means that it is easy enough, using reflection, to detect that a given object exposes this property.
However, I need to be able to access this property in a strongly-typed manner across a selection of the types that implement it.
I am a little surprised that Microsoft didn't make all these classes implement an "IInlineContainer" interface, which would have made type checking and casting very easy.
However, in the absence of such an interface, is there any way to fake this polymorphic functionality, ideally without littering my code with lots of conditions and type checking?
Many thanks for your ideas,
Tim
Edit:
Thanks for your suggestions. A number of people have suggested the idea of a wrapper class, but this is not possible in my situation, as the target objects are not created by my code, but by the other classes in the .NET framework, for example the Xaml parser or the RichTextBox control (in which the containing FlowDocument is being edited).
Edit 2:
There have been several great suggestions here and I thank everyone who shared their ideas. The solution I have chosen to implement employs extension methods, which was suggested by #qstarin, although I have refined the concept to suit my needs, as follows:
public static InlineCollection GetInlines(
this FrameworkContentElement element)
{
if (element == null) throw new ArgumentNullException("element");
if (element is Paragraph)
{
return ((Paragraph) element).Inlines;
}
else if (element is Span) // also catches Bold, Italic, Unerline, Hyperlink
{
return ((Span)element).Inlines;
}
else
{
return null;
}
}
Although this approach requires conditional logic and type casting (which I said I wanted to avoid) the use of extension methods means that it only needs to be implemented in one place, leaving my various calling methods uncluttered.
Extension methods.
public static class InlineContainerExtensions {
public static InlineContainer GetInlines(this Paragraph inlineContainer) {
return inlineContainer.Inlines;
}
public static InlineContainer GetInlines(this Bold inlineContainer) {
return inlineContainer.Inlines;
}
}
If you didn't need to access it in a strongly-typed manner, but just without reflection, you could use dynamic:
dynamic doc = new Bold()
doc.InlineCollection. ...
doc = new Paragraph()
doc.InlineCollection. ...
Another option is to define a wrapper, that exposes a property with the same name, and has an overloaded constructor that takes Bold, Paragraph, etc.
You could implement a wrapper class that exposes an Inlines property and delegates via reflection to the contained object.
Decide if you want to validate that the wrapped object indeed has Inlines in your constructor or when trying to reference it
Employ the Adapter Pattern, write one class for each of those classes you wish to handle, effectively wrapping them in a layer implementing a common layer.
To make the classes discoverable, I would use reflection, tag each such class with an attribute for which class they handle, ie.:
[InlineContainerAdapter(typeof(SpecificClass1))]
public class WrapSpecificClass1 : IInlineContainer
and use reflection to find them.
This would give you several benefits:
You don't have to deal with dynamic, or similar solutions
While you have to use reflection to find the classes, the code you're actually executing once you've created the adapter is 100% yours, hand-coded
You can create adapters for classes that doesn't really implement what you need in the same manner as the rest, by just writing the adapter different
If this sounds like an interesting solution, leave a comment and I'll put up a working complete example.
One way of doing this (apart from using dynamic, which is the easiest solution IMO), you can create dynamically generated methods to return the inlines:
Func<object, InlineCollection> GetInlinesFunction(Type type)
{
string propertyName = ...;
// ^ check whether type has a ContentPropertyAttribute and
// retrieve its Name here, or null if there isn't one.
if (propertyName == null)
return null;
var p = Expression.Parameter(typeof(object), "it");
// The following creates a delegate that takes an object
// as input and returns an InlineCollection (as long as
// the object was at least of runtime-type "type".
return Expression.Lambda<Func<object, InlineCollection>>(
Expression.Property(
Expression.Convert(p, type),
propertyName),
p).Compile();
}
You'd have to cache these somewhere, though. A static Dictionary<Type, Func<object, InlineCollection>> comes to mind. Anyway, when you have, you can simply make an extension method:
public static InlineCollection GetInlines(this TextElement element)
{
Func<object, InlineCollection> f = GetCachedInlinesFunction(element.GetType());
if (f != null)
return f(element);
else
return null;
}
Now, with this in place, just use
InlineCollection coll = someElement.GetInlines();
Because you can check in your GetCachedInlinesFunction whether the property really exists or not, and handle that in a neat fashion, you won't have to litter your code with try catch blocks like you have to when you're using dynamic.
So, your dream-code would be:
foreach (var control in controls) {
var ic = control as IInlineContainer;
if (ic != null) {
DoSomething(ic.Inlines);
}
}
I don't see why you don't want to create a strongly typed wrapper class that uses reflection. With this class (no error handling):
public class InlinesResolver {
private object _target;
public InlinesResolver(object target) {
_target = target;
}
public bool HasInlines {
get {
return ResolveAttribute() != null;
}
}
public InlineCollection Inlines {
get {
var propertyName = ResolveAttribute().Name;
return (InlineCollection)
_target.GetType().GetProperty(propertyName).GetGetMethod().Invoke(_target, new object[] { });
}
}
private ContentPropertyAttribute ResolveAttribute() {
var attrs = _target.GetType().GetCustomAttributes(typeof(ContentPropertyAttribute), true);
if (attrs.Length == 0) return null;
return (ContentPropertyAttribute)attrs[0];
}
}
You could almost get to your dream-code:
foreach (var control in controls) {
var ir = new InlinesResolver(control);
if (ir.HasInlines) {
DoSomething(ir.Inlines);
}
}
You could always superclass them (e.g. InlineParagraph, InlineBold, etc) and have each of your superclasses implement an IInlineContainer interface like you suggested. Not the quickest or cleanest solution, but you at least have them all descending from the same interface.
Depending on your use-case, you could create a public Api that delegated its work to a private method that takes a dynamic. This keeps the strong typing for your public Api and eliminates code duplication, even though it falls back to using dynamic internally.
public void DoSomethingwithInlines(Paragraph p) {
do(p);
}
public void DoSomethingwithInlines(Bolb b) {
do(b);
}
private void do(dynamic d) {
// access Inlines here, using c# dynamic
}