I would like to be able to mark a function somehow (attributes maybe?) so that when it's called from anywhere, some other code gets to process the parameters and return a value instead of the called function, or can let the function execute normally.
I would use it for easy caching.
For example, if I had a function called Add10 and it would look like this:
int Add10 (int n)
{
return n + 10;
}
If the function go called repeatedly with the same value (Add10(7)) it would always give the same result (17) so it makes no sense to recalculate every time. Naturally, I wouldn't do it with functions as simple as this but I'm sure you can understand what I mean.
Does C# provide any way of doing what I want?
I need a way to mark a function as cached so that when someone does Add10(16) some code somewhere is ran first to check in a dictionary is we already know the Add10 value of 16 and return it if we do, calculate, store and return if we don't.
You want to memoize the function. Here's one way:
http://blogs.msdn.com/b/wesdyer/archive/2007/01/26/function-memoization.aspx
Instead of the function, then I would expose a Func<> delegate:
Func<int, int> add10 = (n) =>
{
// do some other work
...
int result = Add10(n); // calling actual function
// do some more perhaps even change result
...
return result;
};
And then:
int res = add10(5); // invoking the delegate rather than calling function
Like Jason mentioned, you probably want something like function memoization.
Heres another SO thread about it:
Whose responsibility is it to cache / memoize function results?
You could also achieve this sort of functionality using principles related to Aspect Oriented Programming.
http://msdn.microsoft.com/en-us/magazine/gg490353.aspx
Aspect Oriented Programming in C#
MbCache might be what you're looking for.
Related
As all coders I hate repeated blocks of code, but as a C++ dev I really want the null checks as it has been burnt into me meaning a have a lot of blocks that look like
if(object == null)
{
//For loops
continue;
//To check function inputs/creation
return; //maybe with a value
}
I know I could put a try/catch around everything, but I really don't like that style of coding
Is there a way to replace the null check block with a generic function. Something like
jumpstatement CheckNull<T>(T thingToCheck)
{
if(thingToCheck == null)
{
return continue;
}
return null;
}
Then in the actual code instead of the old repeated blocks I'd have just the function (padded out as requested)
for(int i = 0; i < myCollection.Count; i++){
//Function forces a "continue;" call if null
CheckNull(myCollection[i]);
//Do some stuff with myCollection[i]
}
The closest thing I could see was talking about code snippits or inline functions but I really don't think that's what I want.
I don't think what you want to do here is possible. Basically, you want to be able to call a function which affects control flow in the function calling it (e.g. you want to be able to return from the calling function from your function). This is not possible with a normal function.
This sort of thing is possible in C/C++ using function-like macros, and in several other languages which support "real" macros. Unfortunately, C# does not have macros, so this sort of thing can't be done in the way you want.
C# 8 has a new feature called nullable reference types that's even better. You add a few annotations here and there, and then the compiler can handle a lot of this for you. You get to just write the code you want to write, without worrying a reference might accidentally be null. It takes some getting used to, but it's pretty cool once you've mastered the concept.
Aside from that, you can't return an arbitrary jump or goto... but you can return a delegate. This is similar to C/C++ function pointer. You can theoretically use this to turn this proposed call:
CheckNull(someObject);
into this:
CheckNull(someObject)();
where the return value of CheckNull() is a method you want to call. But more practically, it would probably look more like this:
CheckNull(someObject, o => {
//Do something with someObject here, where you can be **sure** someObject is not null
});
You could even embed a lock into your method to keep things more thread-safe.
public void CheckNull<T>(T target, Action<T> action)
{
if (target is object)
{ //naive implementation -- potential thread race between these two lines
// ... but it does narrow the race to JUST those two lines, regardless of how much work is hidden in the action.
lock(target)
{
action(target);
}
}
}
The other thing you can do is use Where() operation. So if you have an array like this
object[] items = new object[100];
FillArray(items);
You can write code like this loop over only the items that are not null:
foreach(var item in items.Where(i => i is object))
{
//item will not be null, as long as you're in a single thread. Otherwise, lock on something first.
}
I have two backgroundworkers that are calling one function in an infinite while loop but with different input parameters. There are a lot of variables used in that function.
Question: what is the best approach for defining the variables used inside the function?
If I define the variables globally, the performance is great. BUT, I must use lock a lot of times to make sure there is no conflicts when the variables are modified.
If I define the variables locally inside the function, there would be no conflict (obviously), but the code gets 2-3 times slower. This is as expected, because it is just like defining variables inside loop instead of defining them outside the loop.
One solution is to make another copy of that function and define separate global variables for use for the second thread and second function called in that thread. This may be good in terms of performance, but I believe it is not the most elegant approach.
Any opinion/solution is appreciated.
Create a Class that contains Properties for all the variables. Have each BackgroundWorker create their own instance of this class and pass it to the function as a Argument.
Although I'm not quite clear why your performance slows down 2-3 times if you define these variables in the Function itself.
Are the parameters from each Background Worker effectively "constant"? If so, you could create a function which returns a function - its similar to the solution you've come up with but more elegant because you don't actually need to make copies of the function. Here's a trivial example:
public void RunBackgroundWorkerOne()
{
var myFunction = CreateFunction("Hello ", "World");
while (true)
myFunction();
}
public Func<string> CreateFunction(string value1, string value2)
{
return (value1, value2) =>
{
return String.Format(value1, value2);
};
}
Then each background worker gets its own copy of the function built around the parameters that it wants to use.
Depending on how complex the parameters are for the function you're creating, you may want to create a "parameter map" type of class to make the code clearer.
In C# it's conventional to write in a fairly objective manner, like so:
MyObj obj = new MyObj();
MyReturn ret = obj.DoSomething();
AnotherReturn rett = ret.DoSomethingElse();
I could just write the above like this:
AnotherReturn rett = new MyObj().DoSomething().DoSomethingElse();
However, how does the stackframe work when you have a bunch of function calls in a sequence like this? The example is fairly straightforward but imagine if I've got 50+ function calls chained (this can possibly happen in the likes of JavaScript (/w jQuery)).
My assumption was that, for each function call, a return address is made (to the "dot"?) and the return value (a new object with other methods) is then immediately pumped into the next function call at that return address. How does this work w.r.t. getting to the overall return value (in this example the return address will assign the final function value to rett)? If I kept chaining calls would I eventually overflow? In that case, is it considered wiser to take the objective route (at the cost of "needless" memory assignment?).
It's exactly the same as if you called each method on a separate line, assigning the return value to a variable each time and then using that variable to call the next method.
So your two samples are the same, effectively.
Do you have Reflector? You could try the two methods and inspect the generated IL code to see exactly what differences there are.
Although the 2 calls are same but if you have lot of "Dots" then somewhere it is a code smell (Law of Demeter).
See below discussion
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.
I often find myself using lambdas as some sort of "local functions" to make my life easier with repetetive operations like those:
Func<string, string> GetText = (resource) => this.resourceManager.GetString(resource);
Func<float, object, string> FormatF1 = (f, o) => String.Format("{0:F1} {1}", f, o);
Func<float, object, string> FormatF2 = (f, o) => String.Format("{0:F2} {1}", f, o);
Instead of writing the String.Format-thing over and over, I can happily blow away with FormatF2 e.g. and save myself time and when I need to change something about the formatting, only one place to make edits.
Especially when I need the functionality in the given function exclusively, I'm very reluctant to turn them into a real function. While the lambdas above were relatively small... sometimes I have larger ones like (the following is supposed to add data to a table for print output):
Action<string, string, string> AddSurfaceData = (resource, col, unit) => {
renderTable.Cells[tableRowIndex, 0].Text = "\t" + this.GetText(resource);
renderTable.Cells[tableRowIndex, 1].Text = FormatF2(paraHydReader.GetFloat(paraHydReader.GetOrdinal(col)), "");
renderTable.Cells[tableRowIndex, 1].Style.TextAlignHorz = C1.C1Preview.AlignHorzEnum.Right;
renderTable.Cells[tableRowIndex, 2].Text = " " + this.GetText(unit);
renderTable.Cells[tableRowIndex, 2].Style.TextAlignHorz = C1.C1Preview.AlignHorzEnum.Left;
++tableRowIndex;
};
Again, I need this often and all the benefits of above apply, too. However, as you can see, this one is quite long for a lambda expression.. the question is: When do you draw the line? Is my last lambda too much? What other ways (other than using real functions or trying to stuff the data in containers and loop over them) exist to avoid writing the same code over and over again?
Thanks in advance
Christian
It is something you use potentially many times within a method, and only that inside that method. I like this idea. Do it if it doesn't make your code hard to read. I would say that you should reconsider if you find it difficult to see what is the content of the lambda function vs. what is the real content of the method. In that case it might be cleaner to pull it out in a separate private method.
At the end, this is really a matter of taste...
I agree with awe: for small scale reuse inside a method (or even a class) this is perfect. Like the string.Format examples. I use this quite often. It's basically the same thing as using a local variable for an intermediate value that you use more than once, but then for code.
Your second example seems to be pushing it a bit. Somehow this gives me the feeling a private method AddSurfaceData (possibly static, depending on its use?) would be a better fit. That is of course outside of the context that you have, so use your own good judgement.
A Lambda method is an anonymous method.
This means that you should not give it a name.
If you are doing that, (in your case, you are assigning a name with your reference), it's just another way to declare a function.
C# has already got a way to declare functions, and it's not the lambda way, which was added
uniquely to pass functions via parameters and returns them as return values.
Think, as an example, in javascript:
function f(var1,var2,...,varX)
{
some code
}
or
var f = function() {
some code
}
Different syntax (almost) same thing.
For more information on why it's not the same thing: Javascript: var functionName = function() {} vs function functionName() {}
Another example: in Haskell You can define two functions:
function1 :: Int -> Int
function1 x = x + 2
or
function2 :: Int -> Int
function2 = \x -> x + 2
Same thing (this time I think it's the very same), different syntax. I prefer the first one, it's more clear.
C# 3.5, as Javascript, has got a lot of functional influences. Some of them should it be used wisely, IMHO.
Someone said local lambda functions with assignment in a reference is a good substitute for a method defined within another method, similar to a "let", or a "where" clause in Haskell.
I say "similar" because the twos have very different semantics, for instance, in Haskell I can use function name which is not declared yet and define it later with "where", while in C#, with function/reference assignment I can't do this.
By the way I think it's a good idea, I'm not banning this use of lambda function, I just want to make people think about it.
Every language has got his abstraction mechanism, use it wisely.
I like the idea. I don't see a better way to maintain code locality without violating the DRY principle. And I think it's only harder to read if you're not accustomed to lambdas.
+1 on nikie re DRY being good in general.
I wouldnt use PascalCase naming for them though.
Be careful though - in most cases the stuff you have in there is just an Extract Method in a dress or a potential helper or extension function. e.g., GetText is a Method and FormatF* is probably a helper method...
I have no problem with the long example. I see that you are repackaging compound data very elegantly.
It's the short ones that will drive your colleagues to investigate the advantages of voluntary institutionalization. Please declare some kind of constant to hold your format string and use "that String.Format-thing over and over". As a C# programmer, I know what that does without looking elsewhere for home-spun functions. That way, when I need to know what the formatted string will look like, I can just examine the constant.
I agree with volothamp in general, but in addition ...
Think of the other people that have to maintain your code. I think this is easier to understand than your first example and still offers the maintenance benefits you mention:
String.Format(this.resourceManager.GetString("BasicFormat"), f, o);
String.Format(this.resourceManager.GetString("AdvancedFormat"), f, o);
And your second example appears to be just a different way to declare a function. I don't see any useful benefit over declaring a helper method. And declaring a helper method will be more understandable to the majority of coders.
I personally think its not in good taste to use lambda functions when there is no need for it. I personally wont use a lambda function to replace a simple few lines of procedural code. Lambda functions offer many enhancements, but make the code slightly more complicated to read.
I wouldnt use it to replace string.format.