First of all: I am using C++-CLI, but, as users have asked, I think this also applies to C#, that's why I have added this tag.
I have following function
static CFiducial^ CFiducial::GetCommonBase (array<CFiducial^>^ i_aoFiducial)
{
if (!i_aoFiducial || i_aoFiducial->Length <= 0)
return gcnew CFiducial;
CFiducial^ oFiducial;
for (int iCnt = 0; iCnt < i_aoFiducial->Length; iCnt++)
{
if (!i_aoFiducial[iCnt]) continue;
if (oFiducial)
oFiducial= oFiducial->GetCommonBase (i_aoFiducial[iCnt]);
else
i_aoFiducial[iCnt]->CopyTo (oFiducial);
}
return oFiducial;
}
which is used in identical way in multiple classes.
(There is another member function GetCommonBase (CFiducial^) which compares the member variables content to the content of the members of the passed object and returns a new object with only those members set that are equal. See below for an example).
I now was going to outsource all implementations of this static function and move them to a central location, having only one implementation there. I have tried generics and interfaces, but both fail:
generics don't work because I can't call methods on generics.
interfaces fail because the functions defined in the interface need to take an instance of the object that the interface later is bound to.
This is the interface was going to use:
public interface class ICommonBase
{
ICommonBase^ GetCommonBase (ICommonBase^);
void CopyTo (ICommonBase^%);
};
I could not implement GetCommonBase (ICommonBase^) in the actual classes, I need to implement GetCommonBase (CLASSNAME^), but that does not match the definition in the interface.
Is there a way around this?
Is there another alternative to interface and generics?
I still want to avoid copy and paste of that function into each class where I need it.
Edit
Sample of the member function GetCommonBase(), which is from a different class, where inheritance is actually used, therefore the name. The problem described above has nothing to do with inheritance though.
CImageObject^ CImgObjCircle::GetCommonBase (CImageObject^ i_oImageObject)
{
CImageObject^ oImgObj;
if (!i_oImageObject)
{
this->CopyTo (oImgObj);
return oImgObj;
}
oImgObj = CImageObject::GetCommonBase (i_oImageObject);
CImgObjCircle^ i_oImgObj = dynamic_cast<CImgObjCircle^>(i_oImageObject);
if (!i_oImgObj)
return oImgObj;
CImgObjCircle^ oImgObjLocal = gcnew CImgObjCircle;
oImgObj->CopyTo (oImgObjLocal);
if (m_oDiameterX == i_oImgObj->m_oDiameterX) oImgObjLocal->m_oDiameterX = m_oDiameterX;
return oImgObjLocal;
}
Related
I have this method in C# that looks like I should really refactor it . Should I use a design pattern ? Too much repetition is what I see NOW and especially as MORE conditional if statements get added
Change to a method?
public void CreateOrUpdateReportDefinition(ReportGroupSubReport reportGroupSubReport, bool isNew, int report)
{
if (report == 1)
{
var entity = _envyUnitOfWork.ReportDefinitions.GetById(reportGroupSubReport.Id) ?? new ReportDefinition();
if (isNew)
entity.SetNew();
_envyUnitOfWork.ReportDefinitions.InsertOrUpdate(entity, true);
}
else if (report == 2)
{
var entity = _envyUnitOfWork.TraxReports.GetById(reportGroupSubReport.Id) ?? new TraxReport();
if (isNew)
entity.SetNew();
_envyUnitOfWork.TraxReports.InsertOrUpdate(entity, true);
}
Mapper.Map(reportGroupSubReport, entity);
_envyUnitOfWork.Commit();
}
So what I would do is to put every single conditional behavior into separate method. To avoid repetition you could use the template method pattern. You should also declare your report variable before all if statements so that it would be accessible for the Mapper.Map().
Edit:
Ok, so assuming that both _envyUnitOfWork.TraxReports and _envyUnitOfWork.ReportDefinitions share some common generic interface (which I named Repository in code) defining GetById and InsertOrUpdate methods, you do not need to use any design patterns - simple generic method will do the job. Here is example of the code:
private void createOrUpdateReportDefinition<Report>(ReportGroupSubReport reportGroupSubReport, bool isNew, Repository<Report> repository/*, Action<Report> insertOrUpdate*/) where Report : new()
{
var entity = repository.GetById(reportGroupSubReport.Id) ?? new Report();
if (isNew)
entity.SetNew();
repository.InsertOrUpdate(entity, true);//insertOrUpdate(entity, true);
Mapper.Map(reportGroupSubReport, entity);
_envyUnitOfWork.Commit();
}
public void CreateOrUpdateReportDefinition(ReportGroupSubReport reportGroupSubReport, bool isNew, int report)
{
if (report == 1)
{
createOrUpdateReportDefinition(reportGroupSubReport, isNew, _envyUnitOfWork.ReportDefinitions/*, _envyUnitOfWork.ReportDefinitions.InsertOrUpdate*/);
}
else if (report == 2)
{
createOrUpdateReportDefinition(reportGroupSubReport, isNew, _envyUnitOfWork.TraxReports/*, _envyUnitOfWork.TraxReports.InsertOrUpdate*/);
}
}
Please take under consideration this code is dealing only with one issue in your code which was the code duplication, there are still few things you could improve like removing int report parameter from the method either by dividing it into few methods or at least by replacing it with some enum with meaningful name. I would also suggest the same (dividing the methods) for the bool isNew parameter, since using it means your function doesn't do one thing only which is against single responsibility principle from SOLID - you can read more about it here.
The following refactoring pattern might give you some clues as to how you could manage the proliferating conditional problem: https://sourcemaking.com/refactoring/replace-conditional-with-polymorphism
Edit: The easiest way to do this would be defining an Interface that both TraxReports and ReportDefinition implement that has a InsertOrUpdate method.
Most of the code I have seen deletes the pointer in the finalizer/destructor:
public ref class CPPObjectWrapper
{
private:
CPPObject *_cppObject;
public:
CPPObjectWrapper()
{
_cppObject = new CPPObject();
}
CPPObjectWrapper(IntPtr ^ptr)
{
_cppObject = ptr->ToPointer();
}
~CPPObjectWrapper()
{
delete _cppObject;
_cppObject = 0;
}
!CPPObjectWrapper()
{
if (_cppObject != 0) delete _cppObject;
}
IntPtr^ GetPointer()
{
return gcnew IntPtr(_cppObject);
}
}
My question is what would be standard practice if the library your wrapping does something like this:
void AddObject(CPPObject *cppObject)
{
// adds to a std::list
}
CPPObject* FindObject(/* criteria */)
{
// return reference to std::list item based on criteria
}
If your c# wrapper does this:
void AddObject(CPPObjectWrapper ^cppObject)
{
_internal->addObject(cppObject->GetPointer()->ToPointer());
}
CPPObjectWrapper^ FindObject(/* criteria */)
{
CPPObject *cppObject = _internal->findObject(/* criteria */);
return gcnew CPPObjectWrapper(gcnew IntPtr(cppObjet));
}
You run into a memory issue because your managed object should not delete the pointer because its referenced in another object. The same is true when returning. Would you simply add functionality to tell your managed wrapper not to free the memory when ownership is transferred?
A classic situation when dealing with mixed mode projects, and your suggestion is OK!
It would make sense to have a bool in the constructor that tells it not to destroy the pointer if the same object is used in another non-wrapped object. The ideal case is that every object was wrapped, and the destruction would be done by the CLR.
You can make a generic base class out of this (using the code you already have there), setting the bool by default by the subclass. You are guaranteed to have this functionality many times over. Another tip is to have a virtual OnFinalize() method that is called from the CLR destructor (!) that can do special operations in the subclass, like calling some special free function provided by the native library.
With
public abstract class CompositionPlugin { ... }
and
public class MyCompositionPlugin : CompositionPlugin { ... }
I want to check if an object's type is equal to a given type:
public class Framework {
public IList<CompositionPlugin> CompositionPlugins = new List<CompositionPlugin>();
public CompositionPlugin GetCompositionPlugin(Type ofType)
{
foreach (CompositionPlugin plugin in CompositionPlugins)
{
if (plugin.GetType().Equals(ofType))
return plugin;
}
throw new ArgumentException("A composition plugin of type " + ofType.FullName + " could not be found");
}
}
Where the method is called like this:
Framework framework = new Framework();
// Adding the plugin to the framework is done by loading an assembly and
// checking if it contains plugin-compatible classes (i.e. subclasses
// of <CompositionPlugin>)
framework.RegisterAssembly("E:\\Projects\\Framework\\MyPlugin\\bin\\Debug\\MyPlugin.dll");
CompositionPlugin plugin = framework.GetCompositionPlugin(typeof(MyCompositionPlugin));
Yet, when testing, this check always fails, even though I most definitely have that type of object in the list that I request.
In my understanding, it should return the first instance of MyCompositionPlugin that is found inside the CompositionPlugins-List.
Is my type check wrong? Why? How is it done correctly?
You want to use IsAssignableFrom on your Type:
if (ofType.IsAssignableFrom(plugin.GetType())
Equals only handles cases where types are exactly the same. IsAssignableFrom also handles the case where ofType may be a type that your plugin inherits from, or an interface that is implemented.
Not an answer but too long for a comment...
Are you sure the issue is not in how you call the method or populate your collection?
The comparison itself should be ok, as demonstrated by this simplified version of your code:
class A {}
bool TestType(A item, Type ofType)
{
return item.GetType().Equals(ofType);
}
now:
Console.WriteLine(TestType(new A(), typeof(A))); // True
Console.WriteLine(TestType(new A(), typeof(string))); // False
EDIT
I think #vcsjones is right. You're trying to compare a derived class to a base class.
In the line foreach (CompositionPlugin plugin in CompositionPlugins) you're declaring plugin to be a CompositionPlugin but in the client code you're comparing it with typeof(MyCompositionPlugin). (RE-EDIT no, I'm wrong, your case corresponds to the 4th of my Console.WriteLines that returns true)
See this example with a truth table for Equals in a scenario similar to yours:
class CompositionPlugin {}
class MyCompositionPlugin : CompositionPlugin {}
// Define other methods and classes here
bool TestType(CompositionPlugin item, Type ofType)
{
return item.GetType().Equals(ofType);
}
now
Console.WriteLine(TestType(new CompositionPlugin(),
typeof(CompositionPlugin))); //True
Console.WriteLine(TestType(new CompositionPlugin(),
typeof(MyCompositionPlugin))); //False
Console.WriteLine(TestType(new MyCompositionPlugin(),
typeof(CompositionPlugin))); //False
Console.WriteLine(TestType(new MyCompositionPlugin(),
typeof(MyCompositionPlugin))); //True
use the keyword is
if (plugin is ofType)
return plugin;
EDIT:
I have to go with #vcsjones on this one. Use the isassignablefrom function.
But if you really think it should work, what I always do is create quick function to write debug text to file.
public class Framework {
public IList<CompositionPlugin> CompositionPlugins = new List<CompositionPlugin>();
public CompositionPlugin GetCompositionPlugin(Type ofType)
{
using(var writer = System.IO.File.CreateText(#"C:\test.log"))
{
writer.WriteLine("ofType: " + ofType.toString());
foreach (CompositionPlugin plugin in CompositionPlugins)
{
writer.WriteLine("plugin: " + plugin.GetType().toString());
if (plugin.GetType().Equals(ofType))
return plugin;
}
}
throw new ArgumentException("A composition plugin of type " + ofType.FullName + " could not be found");
}
}
Turns out, the information I initially left out of the question, deeming it not important, was so after all.
The MyCompositionPlugin and CompositionPlugin are both defined in different assemblies, that the executing program loads dynamically at runtime.
The .NET-Runtime now consideres a type loaded from a different assembly another than the one referenced by the executing assembly, rendering the MyCompositionPlugin-Type in the Program to be considered unequal to the MyCompositionPlugin loaded from another assembly, even if they are actually the same.
The solution to comparing the two for equality (in that they are the same "Class" in the common sense) is to break it down to a string-equality of the defining assemblies, which is arguably dirty, but does the trick.
public CompositionPlugin GetCompositionPlugin(Type ofType)
{
foreach (CompositionPlugin plugin in CompositionPlugins)
if (ofType.AssemblyQualifiedName.Equals(plugin.GetType().AssemblyQualifiedName))
return plugin;
throw new ArgumentException("A composition plugin of type " + ofType.FullName + " could not be found");
}
Cudos to Paolo Falabella who pointed to this question
Your problem is most likely due to the fact that the assembly is loaded a second time and therefor the equality fails, it's best to avoid the assembly being loaded again, so you can use normal type comparison instead of needing to use that dirty string comparison. I had the same problem, my plugin interface was defined in a separate assembly, this assembly was present in the start up folder but also in the plugin folder from which the plugin assemblies where dynamically loaded, by consequence interface type equality failed. I removed the interface dll from the plugin folder and after that everything worked as expected.
We're using DI and Unity to work with different dependencies (generally, database and repository classes, dto to entity mappers, etc)
Right now we're trying to create smaller functions that perform tasks that try to be independend from each other, in order to increase testability and also to avoid methods that have lots of different responsibilities, to avoid coupling
One question that I have is, how should DI be used when we have methods that rely on other inner methods, when the nesting is not trivial. For example, consider the following example (just a concept, not real working code):
public ProcessedOrder ProcessOrders(Order inputOrder)
{
foreach (var line in inputOrder.OrderLines)
{
var someData = LineProcessor(line);
}
}
public SomeData LineProcessor(OrderLine line)
{
/* do some stuff*/
var OtherData = ThingProcessor(null,line.SomeStuff);
var ret = new SomeData();
// assign values, more stuff
return ret;
}
public OtherData ThingProcessor(IDep1 someDependency, SomeStuff stuff)
{
someDependency = someDependency ?? ServiceLocator.Resolve<IDep1>();
var ret = someDependency.DoThings(stuff);
return ret;
}
Ok, so far the example shows that we have 3 functions, that could theoretically be called on their own. there's some injected dependency in the ThingProcessor, and if it's null then it tries to resolve it.
However, this is a somehow simple example, but I see something I don't like so much. For instance, I'm calling ThingProcessor with a null value in the first param. So I can say, ok, I modify the signature of LineProcessor to have it injected, so that he pass it in to the other function that needs it. However, he really doesn't need it, it's not its dependency but the function that he's calling.
So here I don't know what approach is the more correct one, if the one that i'm showing, or if I should pass the correlated dependencies across layers. If I do this last thing, then the outermost function will be a mess, because it'll have a long list of dependencies that it will feed to everyone that's below it.
However, the "null approach" I don't like very much, so I'm pretty sure that something's wrong somewhere, and there's probably a better way to design this.
What's the best approach??? Remember, all functions must be used independently (called on their own), so for example I may call just ThingProcessor at some point, or at another one only LineProcessor.
UPDATE :
public CommonPurposeFunctions(IDep1 dep1, IDep2 dep2 ....)
{
this.Dep1 = dep1;
this.Dep2 = dep2;
[...]
}
public ProcessedOrder ProcessOrders(Order inputOrder)
{
foreach (var line in inputOrder.OrderLines)
{
var someData = LineProcessor(line);
}
}
public SomeData LineProcessor(OrderLine line)
{
/* do some stuff*/
var OtherData = ThingProcessor(line.SomeStuff);
var ret = new SomeData();
var morethings = this.Dep2.DoMoreThings();
// assign values, more stuff
return ret;
}
public OtherData ThingProcessor(SomeStuff stuff)
{
var ret = this.Dep1.DoThings(stuff);
return ret;
}
The approach we use is constructor injection, then we store the dependency in a private member field. The container wires up the dependencies; so the number of classes and constructor parameters doesn't really matter.
This works for services. If the dependencies across calls have meaningful state, you will have to pass them in to each call. But, in that case, I'd question if the methods really need to be public methods in their own classes.
You want to end up with a design that eliminates the service locator and truly injects the dependencies.
Does the null object pattern help?
http://en.wikipedia.org/wiki/Null_Object_pattern
I am sure am messing around with a lot of casting and such in this code below. It seems like there should be a smoother way. I'm basically trying to use a builder method (CreateNewPattern) to handle creating new objects of the passed sub-class type (by the CreateNewCircularPattern and CreateNewLinePattern methods). I presently only have two sub-classed types CircularHolePattern and SingleLineHolePattern that inherit from HolePattern, but I expect to have more as my app grows.
Is this a place for using a delegate or a lambda? It know nothing about them, so please be as specific as possible with and code suggestions.
private CircularHolePattern CreateNewCircularPattern()
{
var CreatedPattern = CreateNewPattern(typeof(CircularHolePattern));
return (CircularHolePattern)CreatedPattern;
}
private SingleLineHolePattern CreateNewLinePattern()
{
var CreatedPattern=CreateNewPattern(typeof(SingleLineHolePattern));
return (SingleLineHolePattern)CreatedPattern;
}
private HolePattern CreateNewPattern(Type PatternTypeToCreate)
{
var NewHolePattern = (HolePattern)Activator.CreateInstance(PatternTypeToCreate);
NewHolePattern.PatternName = "Pattern #" + (HolePatterns.Count + 1).ToString();
this.AddPattern(NewHolePattern);
this.SetActivePattern(NewHolePattern);
return NewHolePattern;
}
I suspect you want generics:
private T CreateNewPattern<T>() where T : HolePattern, new()
{
var newHolePattern = new T();
newHolePattern.PatternName = "Pattern #" +
(HolePatterns.Count + 1).ToString();
this.AddPattern(newHolePattern);
this.SetActivePattern(newHolePattern);
return newHolePattern;
}
private SingleLineHolePattern CreateNewLinePattern() {
return CreateNewPattern<SingleLineHolePattern>();
}
private CircularHolePattern CreateNewCircularPattern() {
return CreateNewPattern<CircularHolePattern>();
}
The T is the generic-type-argument; the type we want to create. The where says "it must be HolePattern or a sub-type, and it must have a public parameterless constructor" - this lets us use new T() to create a new instance of it, and access all members of HolePattern against such instances (such as PatternName). This also allows us to call the methods that accept a HolePattern as an argument.
For one, you could reduce the Create...Pattern methods to
private CircularHolePattern CreateNewCircularPattern()
{
return CreateNewPattern(typeof(CircularHolePattern));
}
Another suggestion might be to only work in abstractions. For example, only return HolePattern types from the Create...Pattern methods instead of their concrete types such as CircularHolePattern. You are casting them down to HolePattern in any case.
So, CreateNewCircularPattern becomes
private HolePattern CreateNewCircularPattern()
{
return CreateNewPattern(typeof(CircularHolePattern));
}