Whats the difference between C# delegates, Dynamic Proxy, Closures and function pointers? - language-agnostic

What are useful definitions for the common methods of passing a method or function as data, such as:
Delegates
Closures
Function pointers
Invocation by dynamic proxy and
First class methods?

Function pointers lets you pass functions around like variables. Function pointer is basically legacy method to pass function around in languages that don't support first-class methods, such as C/C++.
First class methods Basically means you can pass functions around like variables. Methods (loosely) mean functions. So this basically means first class functions. In simplest terms, it means functions are treated as "first class citizens", like variables. In the old days (C/C++), because we can't directly pass a function around, and we had to resort to workarounds like function pointers, we said functions weren't first-class citizens.
Delegates is C#'s answer to first-class methods. Delegates are somewhat more powerful because it involves closures, consider the following code snippet:
void foo( int a )
{
void bar() { writefln( a ); }
call( &bar );
}
void call( void delegate() dg ) { dg(); }
int main( char[][] args ) {
foo( 100 );
}
Notice that bar can reference the local variable a because delegates can use closures.
Closures can be very confusing at first. But the lazy-man's definition can be really simple. It basically means a variable can be available in the human-expected way. Put in other words, a variable can be referenced in places where they look like they would be present, by reading the structure of the source code. For example, looking at the code fragment above. If we didn't have closure, bar would not be able to reference a because a was only local to foo, but not bar, which is another function.
Dynamic Proxy is the odd one out. It doesn't belong to these items. Explaining it requires some very long text. It stems from the famous Proxy Pattern. The problem with Proxy Pattern was that the Proxy class needs to be implementing the same interface as the Subject. Dynamic Proxy basically means using reflective approach to discover the Subject's method so that the ProxyPattern can be freed from being tied to the Subject's interface.

just the ones i know about:
Function pointers: just that, a pointer to a piece of code. you jump to it, it executes. typed languages can enforce some parameter passing convention (i.e. C declarations)
Closures: a function with some state paired. most naturally written in lexically scoped languages (i.e. Scheme, JavaScript, Lua). several closures can share the same state (or part of it), making it an easy way to implement OOP.
First class methods: a closure created from an object instance and a method. some languages with both closures and a native OOP (Python, JavaScript) can create closures automatically.

Closure is a programming language concept. Delegate is its realization in MS.NET.
A Delegate in MS.NET is a strongly typed pointer to an object's method (a delegate instance points to both - an object and its method). There is also a way to combine several void delegate instances into one.

Related

Golang testing with functions

I am using a third-party library that is a wrapper over some C functions. Unfortunately, nearly all of the Go functions are free (they don't have a receiver, they are not methods); not the design approach I would have taken but it is what I have.
Using just Go's standard "testing" library:
Is there a solution that allows me to create tests where I can mock functions?
Or is the solution to wrap the library into structures and interfaces, then mock the interface to achieve my goal?
I have created a monte carlo simulation that also process the produced dataset. One of my evaluation algorithms looks for specific models that it then passes the third-party function for its evaluation. I know my edge cases and know what the call counts should be, and this is what I want to test.
Perhaps a simple counter is all that is needed?
Other projects using this library, that I have found, do not have full coverage or no testing at all.
You can do this by using a reference to the actual function whenever you need to call it.
Then, when you need to mock the function you just point the reference to a mock implementation.
Let's say this is your external function:
// this is the wrapper for an external function
func externalFunction(i int) int {
return i * 10 // do something with input
}
You never call this directly but instead declare a reference to it:
var processInt func(int) int = externalFunction
When you need to invoke the function you do it using the reference:
fmt.Println(processInt(5))
Then, went you want to mock the function you just assign a mock implementation to that reference:
processInt = mockFunction
This playground puts it together and might be more clear than the explanation:
https://play.golang.org/p/xBuriFHlm9
If you have a function that receives a func(int) int, you can send that function either the actual externalFunction or the mockFunction when you want it to use the mock implementation.

How do we wrap C++ variable argument parameter in WinRT components

I have a C++ method that takes variable argument as init param. Something like
MyMethod(std::wchar_t*, ...)
Can someone please let me know how can we write a WinRT component wrapper to expose the variable arguments?
WinRT metadata does not support vararg functions, so there is no good way to do this. The answer therefore depends on what the function actually does. Assuming it is some kind of string formatting function I would suggest wrapping it with something like:-
MyMethod(Platform::String^, Windows::Foundation::Collections::IVector<Platform::Object^>^ params);
This will allow you to take the variable arguments.
The problem of course is that this has completely different semantics from what you have. The caller is going to have to pack up an array, and you won't be able to call your existing method easily with the arguments from the vector.

hooking via hotpatching... non exported class method in dll

I have been studying this method of API hooking using the mechanisms for hotpatching in windows dlls.
http://www.codeproject.com/KB/winsdk/0xF9EB_Hooking.aspx
I was wondering if anyone would know of a way to extend that to hooking non exported functions such as a C++ constructor for an internal class inside of a DLL. I have already know the address via dis-assembly... the problem I am having is how to set up the right calling conventions so that I can call the original function inside of my hook function.
I'm already to the point to where my hook function gets called... the program crashes because I can't return the results of calling the original function.
Lets assume we are talking about hooking an internal class constructor with a prototype something like this:
public __thiscall <class_name>::<class_name>(<single pointer arg to another object>)
depending on how your module is loaded, you can generally just overwrite the relative or absolute addresses at their respective call sites, else you need to make a trampolining function, for which its easier to use something like MS Detours.
In terms of the correct prototype for __thiscall based class member functions, you need some trickery, as you can't generally use __thiscall outside classes. The fastest and easiest way is to use __fastcall and ignore the second parameter. So your first definition becomes void __fastcall myctor(myobj* pObj).
Define it as a typical __stdcall function except that you'll have this pointer in ecx register. If you need this pointer, then use the __asm keyword to get the value:
void __stdcall HookedConstructor( SomeObject *pObject){
HookedClass *pClass;
__asm mov pClass, ecx;
...
}
Note that you'll have to do this at the beginning of the call. Otherwise, the value of ecx register may be overwritten.

Actionscript 3 'this' question

I'm aware that's it very common to use this as much as possible when writing ActionScript 3 code (http://www.daveoncode.com/2009/01/07/we-should-always-use-actionscripts-this-keyword/).
But what should be done if you're writing anonymous functions, which don't have appropriate this matching.
x.addEventListener(Event.WHATEVER, function(event:*) {
// When this callback fires, there is a fail:
// because there is no 'this' at this point.
// INVALID!
this.someAction();
});
I saw some recommendations on writing something like:
var self = this;
and then using self in the code of your anonymous functions, but this seems weird.
What's your opinion on this question (for example, do you have something about it in your coding standard)?
Since you're using anonymous function, there is no this (per se).
By defining self you are defining a local scope variable that can be then called by reference... personally, I don't like the practice.
Do you have a specific reason for using anonymous functions over named functions? To quote Grant Skinner:
in almost every case, the use of an
anonymous function in your code
indicates an architectural problem.
There are almost no real uses for
anonymous functions – they are less
efficient, much harder to debug, and
far harder to grok when reading code.
Here is an interesting discussion about functions and scope from Mike Chamber's blog:
http://www.mikechambers.com/blog/2008/10/08/function-closures-and-this-in-actionscript-3/
If you scroll down near the bottom of the comments you can find Grant's response.
We have a similar approach (so this isn't an answer as much as it is affirmation of your approach):
public class myClass extends EventDispatcher{
public function foo() : void {
var thisObject : myClass = this;
this.addEventListener(EVENT, function(event : Event) : void {
thisObject.foo_internal();
}, false, 0, true);
}
protected function foo_interal() : void {
}
}
Of course, the purist might say that you shouldn't be adding listeners in a manner that prevents you from removing them! That said, we use this convention in other places where we use inner functions outside the context of a listener.
Edited: Ah - my bad, I misunderstood. I typically don't refer to this unless it's a self-contained action, etc. Using self or something similar provides a means for other methods to access it. I personally approach development from this standard, for removing listeners, etc..
Hope that helps a little.
You can either use methods so "this" will be fixed to the instance, or stop using "this" so Flash Player will search the scope chain. I prefer letting Flash Player search the scope chain because I think code with "this" everywhere is hard to read.

Usage of initialize() vs. setup() in Mootools

Mootools classes have an initialize() method that's called when a new object is instantiated.
It seems that setup() is a commonly used method as well.
Most classes I've observed call this.setup() from initialize() and nowhere else, which has left me wondering:
What's the purpose of setup()? Why not just put the setup() code in initialize()? When does it make sense to use a setup() method?
as oskar says, there's no benefit to using that very name. If you wanted to, you could only use a single initialize function with a bunch of anonymous functions within and events but it does not make for very easy code to read, extend and maintain.
i tend to use methods like this.setupScene() and this.attachEvents() to abstract different actions. within these methods, i tend to loop through items and call smaller pseudo-private methods that do the singular dom manipulation required or element.addEvent, aka, this.elements.each(function(el) { this._attachEvent(el, "something"); }, this);
If you are sharing code with other users, there are certain conventions most mootools authors try to adhere to when releasing plugins or contributing to the core and more forks.
for example, if the class relates to an element or an array of elements, always set this.element = document.id(el); etc.
for reference on best practices: http://ryanflorence.com/11-tips-for-creating-great-mootools-plugins/
or even http://davidwalsh.name/mootools-class-tips
after a while, they start making perfect sense and will help you tremendously in your work.
There is no benefit whatsoever in using a setup/build/whatever function that is only called from the initialize function of a mootools Class.
I guess the distinction comes from languages where you don't have variable function arguments but rather overload function names with different sets of arguments. Like Java.
In Java this makes perfect sense. When you have multiple constructors that differ in the arguments they accept, then you handle the argument specific operations in your constructor and the common stuff, that every constructor needs to call in a method that is called by all constructors.
Personally I don't make this distinction in my mootools Classes, but rather only outsource functionality in its own function, if there is need to reuse the code from another function.
Don't get confused by setup functions, there is no hidden power to them.
setup is not a private MooTools method. It's not going to do anything until you create an actual method named this way.
There's one instance of this method in MooTools-more, and it's nothing beyond a simple keyword, just like createDefaults() or setInitialStuff() would be.
Keep in mind that MooTools classes are all about extending and reusing existing code. When you extend a class, you might want to change the initialization, but not the setup code. Of course you can run the parent initializer by using this.parent(), but that might introduce unwanted side-effects.
Take this (very simple) example (view live):
var Counter = new Class({
initialize: function(i){
this.i = i;
this.setup();
},
setup: function(){
new Element('p', {
'text': this.i
}).inject(document.body);
}
});
var MultiplyCounter = new Class({
Extends: Counter,
initialize: function(i){
this.i = i * 2;
this.setup();
}
});
new Counter(5);
new MultiplyCounter(5);
The extended class only changes the initialization of i, not the whole implementation of the class. For more complex classes, this creates faster (initialization is only run once) and cleaner (divide and conquer) code.