Stubbing a dictionary in Rhino.Mocks - vb.net

I have a read-only dictionary on a dependency that I'd like to be able to stub with return values, and check that assignments to it have happened.
I was hoping that Rhino.Mocks would create an empty dictionary for me by default, but unfortunately it doesn't. Since it is read-only, I can't create a new dictionary and assign it to that property.
I was hoping to be able to stub it instead. From what I understand, the C# syntax for this would looking something like this:
m.Stub(x => x.myProperty).Return("abc");
So I was hoping that this would work for VB:
m.Stub(sub(x) x.myProperty).Return("abc");
But it doesn't (compiler error). Any ideas on how to accomplish this? I'm open to the Expect/Verify syntax if it can accomplish this...

Using Function will do the trick:
m.Stub(Function(x) x.myProperty).Return("abc")
If you want to verify whether myProperty got called you could use Expect instead of Stub:
m.Expect(Function(x) x.myProperty).Return("abc")
// Some code here
m.VerifyAllExpectations()

Related

What is indirect object notation, why is it bad, and how does one avoid it?

The title pretty much sums it up, but here's the long version anyway.
After posting a small snippet of perl code, I was told to avoid indirect object notation, "as it has several side effects". The comment referenced this particular line:
my $some_object = new Some::Module(FIELD => 'value');
As this is how I've always done it, in an effort to get with the times I therefore ask:
What's so bad about it? (specifically)
What are the potential (presumably negative) side effects?
How should that line be rewritten?
I was about to ask the commenter, but to me this is worthy of its own post.
The main problem is that it's ambiguous. Does
my $some_object = new Some::Module(FIELD => 'value');
mean to call the new method in the Some::Module package, or does it mean to call the new function in the current package with the result of calling the Module function in the Some package with the given parameters?
i.e, it could be parsed as:
# method call
my $some_object = Some::Module->new(FIELD => 'value');
# or function call
my $some_object = new(Some::Module(FIELD => 'value'));
The alternative is to use the explicit method call notation Some::Module->new(...).
Normally, the parser guesses correctly, but the best practice is to avoid the ambiguity.
What's so bad about it?
The problems with Indirect Method Notation are avoidable, but it's far easier to tell people to avoid Indirect Method Notation.
The main problem it's very easy to call the wrong function by accident. Take the following code, for example:
package Widget;
sub new { ... }
sub foo { ... }
sub bar { ... }
sub method {
...;
my $o = new SubWidget;
...;
}
1;
In that code, new SubWidget is expected to mean
SubWidget->new()
Instead, it actually means
new("SubWidget")
That said, using strict will catch most of these instances of this error. Were use strict; to be added to the above snippet, the following error would be produced:
Bareword "SubWidget" not allowed while "strict subs" in use at Widget.pm line 11.
That said, there are cases where using strict would not catch the error. They primarily involve the use of parens around the arguments of the method call (e.g. new SubWidget($x)).
So that means
Using Indirect Object Notation without parens can result in odd error messages.
Using Indirect Object Notation with parens can result in the wrong code being called.
The former is bearable, and the latter is avoidable. But rather than telling people "avoid using parens around the arguments of method calls using Indirect Method Notation", we simply tell people "avoid using Indirect Method Notation". It's just too fragile.
There's another issue. It's not just using Indirect Object Notation that's a problem, it's supporting it in Perl. The existence of the feature causes multiple problems. Primarily,
It causes some syntax errors to result in very odd/misleading error messages because the code appeared to be using ION when it wasn't.
It prevents useful features from being implemented since they clash with valid ION syntax.
On the plus side, using no indirect; helps the first problem.
How should that line be rewritten?
The correct way to write the method call is the following:
my $some_object = Some::Module->new(FIELD => 'value');
That said, even this syntax is ambiguous. It will first check if a function named Some::Module exists. But that's so very unlikely that very few people protect themselves from such problems. If you wanted to protect yourself, you could use the following:
my $some_object = Some::Module::->new(FIELD => 'value');
As to how to avoid it: There's a CPAN module that forbids the notation, acting like a pragma module:
no indirect;
http://metacpan.org/pod/indirect
The commenter just wanted to see Some::Module->new(FIELD => 'value'); as the constructor.
Perl can use indirect object syntax for other bare words that look like they might be methods, but nowadays the perlobj documentation suggests not to use it.
The general problem with it is that code written this way is ambiguous and exercises Perl's parser to test the namespace to e.g. check when you write method Namespace whether Namespace::method exists.

Runtime method to get names of argument variables?

Inside an Objective-C method, it is possible to get the selector of the method with the keyword _cmd. Does such a thing exist for the names of arguments?
For example, if I have a method declared as such:
- (void)methodWithAnArgument:(id)foo {
...
}
Is there some sort of construct that would allow me to get access to some sort of string-like representation of the variable name? That is, not the value of foo, but something that actually reflects the variable name "foo" in a local variable inside the method.
This information doesn't appear to be stored in NSInvocation or any of its related classes (NSMethodSignature, etc), so I'm not optimistic this can be done using Apple's frameworks or the runtime. I suspect it might be possible with some sort of compile-time macro, but I'm unfamiliar with C macros so I wouldn't know where to begin.
Edit to contain more information about what I'm actually trying to do.
I'm building a tool to help make working with third-party URL schemes easier. There are two sides to how I want my API to look:
As a consumer of a URL scheme, I can call a method like [twitterHandler showUserWithScreenName:#"someTwitterHandle"];
As a creator of an app with a URL scheme, I can define my URLs in a plist dictionary, whose key-value pairs look something like #"showUserWithScreenName": #"twitter://user?screenName={screenName}".
What I'm working on now is finding the best way to glue these together. The current fully-functioning implementation of showUserWithScreenName: looks something like this:
- (void)showUserWithScreenName:(NSString *)screenName {
[self performCommand:NSStringFromSelector(_cmd) withArguments:#{#"screenName": screenName}];
}
Where performCommand:withArguments: is a method that (besides some other logic) looks up the command key in the plist (in this case "showUserWithScreenName:") and evaluates the value as a template using the passed dictionary as the values to bind.
The problem I'm trying to solve: there are dozens of methods like this that look exactly the same, but just swap out the dictionary definition to contain the correct template params. In every case, the desired dictionary key is the name of the parameter. I'm trying to find a way to minimize my boilerplate.
In practice, I assume I'm going to accept that there will be some boilerplate needed, but I can probably make it ever-so-slightly cleaner thanks to NSDictionaryOfVariableBindings (thanks #CodaFi — I wasn't familiar with that macro!). For the sake of argument, I'm curious if it would be possible to completely metaprogram this using something like forwardInvocation:, which as far as I can tell would require some way to access parameter names.
You can use componentsSeparatedByString: with a : after you get the string from NSStringFromSelector(_cmd) and use your #selector's argument names to put the arguments in the correct order.
You can also take a look at this post, which is describing the method naming conventions in Objective C

Create selector dynamically from string

I've made a program that uses reflection to add Traits dynamically, and solves conflicts automatically in one predeterminated way.
It uses aliases. It's working (I think), but I have only a problem when finally adding the trait.
My program generates all the aliases for each conflicting method, and add them with the trait to the class. The problem is that I'm not able to generate the selector correctly, its generating a string instead.
For example:
I need this
TCircle # {#circleHash -> #hash}
but I'm generating this
TCircle # {'#circleHash' -> #hash}
you can see the quotes in #circleHash.
Because is a meta-program, it generates also dynamically the selector.
How I can get it without the quotes and with the #?
I need to able to do something like this
"have the selector name in string"
obj := 'SelectorDinamicallyGenerated'.
^(#obj)
and get #SelectorDinamicallyGenerated, and not '#SelectorDinamicallyGenerated'.
How can I do this?
I've tried doing like that (#obj) but it is not working (getting #obj)
I've found it.
It's
obj asSymbol
Good you found it yourself. Maybe it is just irritating that in smalltalk a symbol is a selector. It is just not the case that there is a selector class and you could do "aString asSelector". So
'foo' asSymbol => #foo
will do. If you need to generate a setter you can do
'foo' asSymbol asMutator => #foo:

Test method existence on Objects

I have a cell array of Matlab objects, something like:
objs = {Object1(), Object2(), Object3()};
These objects are all of different types. Some of them will have a method, let's call it myMethod(). I want to do something like:
for o = objs
if hasMethod(o, 'myMethod()')
o.myMethod();
end
end
and my difficulty is that I don't know how to do hasMethod - exist doesn't seem helpful here.
I could use a try - catch, but I'd rather do something neater. Is there a way to do this? Should I just change my design instead?
Another option is to use the meta class.
obmeta = metaclass(ob);
methodNames = cellfun(#(x){x.Name},obmeta.Methods);
You can also get additional information from obmeta.Methods like
Amount of input/output parameters.
Access type
In which class the method is defined.
Also, metaclass can be constructed from the name of the class, without an instance, which can be an advantage in some situations.
Ah, found it. Not very exciting - you can get a list of methods with the methods command. So to check if an object has a method,
if any(strcmp(methods(o), 'myMethod'))
o.myMethod();
end
Very close! If you had written the function name a bit differently you would've stumbled upon the following built-in:
if ismethod(o, 'myMethod')
o.myMethod();
end
Documentation: ismethod.
Why would you want to do that? You'd better have a good reason :p
Better make them inherit a general function from a superclass. Then you can just call that function for all of them, instead of looking up which class it is/checking if a function exists and then calling a function depending on the result (which is imo not very OO)
One simple option is to use the function EXIST (along with the function CLASS) to check if the method exists for the given class:
if exist(['#' class(o) '/myMethod'])
o.myMethod();
end
Another option is to use the function WHICH to perform the check like this:
if ~isempty(which([class(o) '/myMethod']))
o.myMethod();
end

Cpp . NET: "a->Methodname " vs "a.MethodName"

I would like to know the difference between these two (sorry I do not know the name of this subject).
I come from C# where I was used to write System.data as well as classA.MethodA. I have already found out that in Cpp, with namespaces I need to use ::, with classmembers ->. But what about simple "."?
I have created System::data:odbc::odbcConnection^ connection. Later I was able to use connection.Open. Why not connection->open?
Im sorry, I am sure its something easily findable on the net, but I dont know english term for these.
Thank you guys
If you have a pointer to an object, you use:
MyClass *a = new MyClass();
a->MethodName();
On the other hand, if you have an actual object, you use dotted notation:
MyClass a;
a.MethodName();
To clarify the previous answers slightly, the caret character ^ in VC++ can be thought of as a * for most intents and purposes. It is a 'handle' to a class, and means something slightly different, but similar. See this short Googled explanation:
http://blogs.msdn.com/branbray/archive/2003/11/17/51016.aspx
So, in your example there, if you initialize your connection like:
System::Data::Odbc::OdbcConnection connect;
//You should be able to do this:
connect.Open();
Conversely, if you do this:
System::Data::Odbc::OdbcConnection^ connect1 = gcnew System::Data::Odbc::OdbcConnection();
connect1.Open(); // should be an error
connect1->Open(); //correct
The short answer: C++ allows you to manage your own memory. As such, you can create and manipulate memory, through usage of pointers (essentially integer variables containing memory addresses, rather than a value).
a.Method() means a is an instance of a class, from which you call Method.
a->Method() means a is a pointer to an instance of a class, from which you call Method.
When you use syntax like a->member, you are using a pointer to a structure or object.
When you use syntax like a.member, you are using the structure or object and not a pointer to the structure or object.
I did a quick google for you and THIS looks fairly quick and decent explanation.