I have a dll file, and I took an object from it and called the functions inside this dll by the object, like this:
Command testClass = (Command)assembly.CreateInstance(creatObject);
testClass.Execute();
I used reflection for some reason. So I need to use invoke function & set values for variables, then calling the basic function Execute.
Previously I wrote the following:
object returnValue = objectType.GetMethod("setValues").Invoke(classObject, arguments);
testClass.Execute();
but it wasn't useful for me.
I used the following:
object returnValue = objectType.GetMethod("setValues").Invoke(classObject, arguments);
object returnValue1 = objectType.GetMethod("Execute").Invoke(classObject, null);
I just want to ask if this is right, to calling the execute in this way, and by the way it works!
Calling methods using Reflection the way you use it is "okay" as long as you know what you're doing. There are quite a few things to consider when using Reflection:
It is unsafe - you can very easily make a mistake - if you change the method name, you won't be notified by the compiler and you'll discover that at runtime
It is slow - Reflection is simply inefficient - calling a method is slower by orders of magnitude.
If you need to do this only rarely, then it may be fine. However, your initial approach using a shared base class Command appears to be a much better idea to me. Could you clarify why you decided to use Reflection, so that we can (perhaps) suggest a better way?
If you need dynamic invocation, you could also consider using C# 4.0 dynamic, which does all this stuff behind the scene for you and is more efficient than simple Reflection. However, you should still have a very good reason for doing this.
It's not right, why do you use Reflection, provide a common interface and call the method directly. If you don't know why you use reflection then it's wrong :)
If you are implementing a extensible system, perhaps MEF would be better?
Thanks for your answers, sure i know why i used Reflection.
Because i need to set the values for a function setValues(i, j..etc) in run time, and these parameters and their names are different from dll to another.
then i have to invoke this function with its current values, & finally run another function named Execute() with the same current values, which could be changed from execute to another for the program!
so when i just used:
object returnValue = objectType.GetMethod("setValues").Invoke(classObject, arguments);
testClass.Execute();
the execute didnt work with the run time values which been entered.
But by this :
object returnValue = objectType.GetMethod("setValues").Invoke(classObject, arguments);
object returnValue1 = objectType.GetMethod("Execute").Invoke(classObject, null);
it works.
So i just want to be sure, that my work is right and not only suitable for my case!
Related
I am a student and I am currently preparing for my OOP Basics Exam.
When in the controller you have methods which return a value and such that are void - how do you invoke them without using a if-else statement?
In my code "status" is the only one which should return a string to be printed on the Console - the others are void. So I put a if-esle and 2 methods in the CommandHandler.
Since I know "if-else" is a code smell, is there a more High Quality approach to deal with the situation?
if (commandName == "status")
{
this.Writer.WriteLine(this.CommandHandler.ExecuteStatusCommand(commandName));
}
else
{
this.CommandHandler.ExecuteCommand(commandName, commandParameters);
}
This is the project.
Thank you very much.
First, don't worry about if/else. If anybody tells you if/else is a code smell, put it through the Translator: What comes out is he's telling you he's too crazy, clueless, and/or fanatical to be taken seriously.
If by ill chance you get an instructor who requires you to say the Earth is flat to get an A, sure, tell him the Earth is flat. But if you're planning on a career or even a hobby as a navigator, don't ever forget that it's actually round.
So. It sounds to me like CommandHandler.ExecuteStatusCommand() executes the named command, which is implemented as a method somewhere. If the command method is void, ExecuteStatusCommand() returns null. Otherwise, the command method may return a string, in which case you want to write it to what looks like a stream.
OK, so one approach here is to say "A command is implemented via a method that takes a parameter and returns either null or a string representing a status. If it returns anything but null, write that to the stream".
This is standard stuff: You're defining a "contract". It's not at all inappropriate for command methods which actually return nothing to have a String return type, because they're fulfilling the terms of contract. "Return a string" is an option that's open to all commands; some take advantage, some don't.
This allows knowledge of the command's internals to be limited to the command method itself, which is a huge advantage. You don't need to worry about special cases at the point where you call the methods. The code below doesn't need to know which commands return a status and which don't. The commands themselves are given a means to communicate that information back to the caller, so only they need to know. It's incredibly beneficial to have a design which allows different parts of your code not to care about the details of other parts. Clean "interfaces" like this make that possible. The calling code gets simpler and stays simpler. Less code, with less need to change it over time, means less effort and fewer bugs.
As you noted, if you've got a "status" command that prints a result, and then later on you add a "print" command that also prints a result, you've got to not only implement the print command itself, but you've also got to remember to return to this part of your code and add a special case branch to the if/else.
That kind of tedious error-prone PITA is exactly the kind of nonsense OOP is meant to eliminate. If a new feature can be added without making a single edit to existing code, that's a sort of Platonic ideal of OOP.
So if ExecuteCommand() returns void, we'll want to be calling ExecuteStatusCommand() instead. I'm guessing at some things here. It would have been helpful if you had sketched out the semantics of those two methods.
var result = this.CommandHandler.ExecuteCommand(commandName, commandParameters);
if (result != null)
{
this.Writer.WriteLine(result);
}
If my assumptions about your design are accurate, that's the whole deal. commandParameters, like the status result, are an optional part of the contract. There's nothing inherently wrong with if/else, but sometimes you don't need one.
I acknowledge that they can be useful, but I'm trying to wrap my head around when I would actually want to have a func as a parameter of a method.
public void WeirdMethod(int myNumber, func op);
In terms of design and functionality, could someone explain to me some circumstances where I would want to consider this? Theories of "reusability" isn't going going to help me much. Real world scenarios would be best. Help me think like you lol.
Here's about all I know:
This would allow me to pass a delegate
This would allow me to use a lambda expression.
Yeap...
NOTE:
I know this thread will get closed since there's no "right" answer. But I think what clicked it for me just now was "delayed calculation".
Deferring operations until a later time. A very practical example is deferring change tracking until an object tree is fully populated. Each type or repository can tell you what it wants done, and the caller can decide when to actually do it.
Composition of logic (as Justin Niessner mentioned).
Abstraction, e.g. ("here's a contract that has inputs and ouputs, but I don't care what it's implementation is as long as it fulfills the contract). For example, you could pass a "statusWriter" Func to a method which might write to a console, debug window, log file, database, or do nothing at all. All the consuming method knows is that it consumes a type and invokes it when desired.
Along the same lines, passing a Func to a method allows an abstracted and simple way of allowing a where predicate to be defined by the caller. I use this paradigm frequently to support a strongly-typed filter to be applied to a result (not talking about LINQ to SQL, just filtering a list of information as the caller sees fit).
Elegant functional paradigms, such as this example which demonstrates recursion using anonymous functions. These constructs would be verbose/impossible without the ability to pass one function to another (especially in an abbreviated form).
A general scenario is when you must pass a delayed calculation to your method. This is useful when calculating something is expensive, for example, when you cache something.
public Guid GetFromCache(string key, Func<Guid> make) {
Guid res;
if (!cache.TryGetValue(key, out res)) {
res = make();
cache.Add(key, res);
}
return res;
}
Now you can call this method as follows:
Guid guid = GetFromCache(myKey, () => database.MakeNewGuid());
If you had something asynchronous and you wanted to give it a callback method?
They enable to you to Curry functions as well as use Functional Composition.
While you've almost certainly used delegates before (since that's what events are), LINQ is a prime example for when passing a delegate as a function parameter is useful.
Think about Where. You're supplying a piece of logic (specifically a definition of what meets your criteria--whatever they are) to a function that uses it as part of its execution.
At the top of my program I have a code segment that looks like this
var XXXAssembler = new XXXAssembler(ctx);
XXXAssembler.LoadXXX();
var YYYAssembler = new YYYAssembler(ctx );
YYYAssembler.LoadYYY();
var ZZZAssembler = new ZZZAssembler(ctx);
ZZZAssembler.LoadZZZ();
In the above logic I use each varaible once to call the respective loader, and I don't use the variables anywhere else.
I can change the code to this
new XXXAssembler(ctx).LoadXXX();
new YYYAssembler(ctx ).LoadYYY();
new ZZZAssembler(ctx).LoadZZZ();
This reduces the size of the code, but I'd like to think it simplifies it as well. I could see the usefulness of variables for debugging, but I don't think that's necessarily a good reason. Others may disagree.
Is the non-varaible version considered bad coding style?
Unless you're going to use the object assigned to the Assembler variable, then there's no need for it.
I'd say get rid of it, clean up the code, and then if you need it later you can bring it back.
new XXXAssembler(ctx).LoadXXX(); is absolutely fine as long as you don't have use the reference returned by new XXXAssembler(ctx) elsewhere.
If u ask me, the size of the code doesn't matters. Only matter is that, when you see the code 1 year later, to know how it does what it needs to do, and how to rewrite / reuse / etc.
As you mention, the only technical reason to assign the created object to a variable is if you need to use it or look at it somewhere. If you're confident that you'll never need to do this, you don't need to create a new variable, and you can shorten up your code a bit.
But I'll offer up two caveats:
(1) I often find that I need to look at the output of a method before it returns, or at the instance of the object created by the new statement when I'm debugging. So sometimes instead of doing this:
public MyObject ReturnSomeObject()
{
return new MyObject();
}
I'll do this instead:
public MyObject ReturnSomeObject()
{
var myObject = new MyObject();
return myObject;
}
Just so I can look at it in the debugger. It clutters up my code a bit, but it can be very helpful when I'm trying to figure out why something else went wrong.
(2) If you find that you can do the sort of thing you're describing very often, you may want to take a harder look at how your classes are structured. What's the point of a class that has a method that returns nothing and which doesn't modify the internal state of the class in any fashion that you're interested in? To take your example above, presumably your various LoadXXX() methods should return some sort of status code, or modify some status property of the object, or return a pointer to the file that they loaded, or, well, something. If they do, but you're not bothering to look at it - well, that's another problem. If the methods really don't need to modify any aspect of the object's internal state, then you should look strongly at making them static: it allows you to avoid running the class constructor each time you call them, it expresses their intent more clearly, and it allows the compiler to notify you of a possible inconsistency if you do decide that they need to modify the object state at some point in the future.
Nothing hard-and-fast here, just some guidelines.
If you are never going to use the Object again, but for this case, I don't see the point in giving them names. It adds needless lines of clutter to your code.
I think not assiging to a variable is fine. I do this in many cases, e.g. for some unittest mocks new Mock<IInterfaceToMock>.Object or for callbacks functors SomeFunctionAcceptingCallback(args, new CallbackHandler()).
When using extremely short-lived objects that I only need to call one method on, I'm inclined to chain the method call directly to new. A very common example of this is something like the following:
string noNewlines = new Regex("\\n+").Replace(" ", oldString);
The point here is that I have no need for the Regex object after I've done the one replacement, and I like to be able to express this as a one-liner. Is there any non-obvious problem with this idiom? Some of my coworkers have expressed discomfort with it, but without anything that seemed to be like a good reason.
(I've marked this as both C# and Java, since the above idiom is common and usable in both languages.)
This particular pattern is fine -- I use it myself on occasion.
But I would not use this pattern as you have in your example. There are two alternate approaches that are better.
Better approach: Use the static method Regex.Replace(string,string,string). There is no reason to obfuscate your meaning with the new-style syntax when a static method is available that does the same thing.
Best approach: If you use the same static (not dynamically-generated) Regex from the same method, and you call this method a lot, you should store the Regex object as a private static field on the class containing the method, since this avoids parsing the expression on each call to the method.
I don't see anything wrong with this; I do this quite frequently myself.
The only exception to the rule might be for debugging purposes, it's sometimes necessary to be able to see the state of the object in the debugger, which can be difficult in a one-liner like this.
If you don't need the object afterwards, I don't see a problem - I do it myself from time to time as well. However, it can be quite hard to spot, so if your coworkers are expressing discomfort, you might need to put it into a variable so there are no hard feelings on the team. Doesn't really hurt you.
You just have to be careful when you're chaining methods of objects that implement IDisposable. Doing a single-line chain doesn't really leave room for calling Dispose or the using {...} block.
For example:
DialogResult result = New SomeCfgDialog(some_data).ShowDialog();
There is no instance variable on which to call Dispose.
Then there is potential to obfuscate intent, hurt rather than improve readability and make it tougher to examine values while debugging. But those are all issues particular to the object and the situation and the number of methods chained. I don't think that there is a single reason to avoid it. Sometimes doing this will make the code more concise and readable and other times it might hurt for some of the reasons mentioned above.
As long as you're sure that the object is never needed again (or you're not creating multiple instances of an identical object), then there's no problem with it.
If the rest of your team isn't comfortable with it, though, you might want to re-think the decision. The team should set the standards and you should follow them. Be consistent. If you want to change the standard, discuss it. If they don't agree, then fall in line.
I think thats ok, and would welcome comments/reasons to the contrary. When the object is not short lived (or uses unmanaged resources - ie COM) then this practice can get you into trouble.
The issue is readability.
Putting the "chained" methods on a separate line seems to be the preferred convention with my team.
string noNewlines = new Regex("\\n+")
.Replace(" ", oldString);
One reason to avoid this style is that your coworkers might want to inspect the object in a debug mode. If you compound the similar instantiation the readability goes down a lot. For example :
String val = new Object1("Hello").doSomething(new Object2("interesting").withThis("input"));
Generally I prefer using a static method for the specific example you have mentioned.
The only potential problem I could see is - if, for some reason, new Regex were NULL because it was not instantiated correctly, you would get a Null Pointer Exception. However, I highly doubt that since Regex is always defined...
If you don't care about the object you invoke the method on, that's a sign that the method should probably be static.
In C#, I'd probably write an extension method to wrap the regex, so that I could write
string noNewlines = oldString.RemoveNewlines();
The extension method would look something like
using System.Text.RegularExpressions;
namespace Extensions
{
static class SystemStringExtensions
{
public static string RemoveNewlines(this string inputString)
{
// replace newline characters with spaces
return Regex.Replace(inputString, "\\n+", " ");
}
}
}
I find this much easier to read than your original example. It's also quite reusable, as stripping newline characters is one of the more common activities.
I've recently been tasked with adding logging statements to every method call in a solution. These log entries need to contain the class and method name.
I know I can use MethodBase.GetCurrentMethod() and the StackFrame.GetMethod() methods. Which is better? Is there a better (or more performant) way to get the class and method name?
Well, the best/fastest way is to include a string in every function. That may not appear the most practical solution, but MethodBase.GetCurrentMethod() requires coding inside every method that using it anyway. i.e. You can write
string funcName = "MyClass.MyFunction(int, int)";
or you can write
string funcName = MethodBase.GetCurrentMethod().Name
Now, if you want to get the Name of the function that called the current function (i.e., you want to do this in one spot in your logging function), then your only option is reading through the StackFrame.
I have two suggestions:
Use ready-made AOP frameworks (like http://www.sharpcrafters.com/ ) they can handle this easily
Do a custom prebuild action where you replace some kind of stub in the beginning of every method:
void PerformSomeAction()
{
//PUT_LOGGING_HERE
}
then in custom tool replace those stubs with method names. This is guaranteed fastest method, but requires some investments.
this.getType().toString() should get you the class
About the method it seems stackFrame and methodbase are the most obvouis solutions, I cant comment on which is more efficient.