I wanna understand why this syntax works, and how - actionscript-3

I've seen a very strange thing that i know it works, but i can't seem to understand exactly why and how this works.
i have a line of code that reads this:
_game._requestedState = new (FlxU.getClass(FlxU.getClassName(_game._state,false)))();
Ok, so what i can see here, is, i'm invoking an annonymous constructor, by reflection. Is that it?
A simple yes would do as an answer.
A no with an explanation about how and why this works would be perfect.
Thanks.

There's no such thing as an anonymous constructor.
The method is called FlxU.getClassName, which makes it clear that there is in fact a name involved. It takes some _game._state, get's a class name from it and then gets the actual class from that name.
This is similar to getDefinitionByName(), which it likely uses internally.

Related

Java supplier interface with org.powermock.reflect.exceptions.MethodNotFoundException

I have mock a https://github.com/elastic/elasticsearch/blob/master/core/src/main/java/org/elasticsearch/client/transport/TransportClient.java with Powermockito, before it works, but since the code chanage and add below code:
NetworkModule networkModule = new NetworkModule(settings, true, pluginsService.filterPlugins(NetworkPlugin.class), threadPool,
bigArrays, circuitBreakerService, namedWriteableRegistry, xContentRegistry, networkService);
final Transport transport = networkModule.getTransportSupplier().get();
the code alway fail at getTransportSupplier().get(), the throws exception:
Caused by: org.powermock.reflect.exceptions.MethodNotFoundException: No methods matching the name(s) get were found in the class hierarchy of class java.lang.Object.
at org.powermock.reflect.internal.WhiteboxImpl.getMethods(WhiteboxImpl.java:1720)
at org.powermock.reflect.internal.WhiteboxImpl.getMethods(WhiteboxImpl.java:1745)
at org.powermock.reflect.internal.WhiteboxImpl.getBestMethodCandidate(WhiteboxImpl.java:983)
at org.powermock.core.MockGateway$MockInvocation.findMethodToInvoke(MockGateway.java:317)
at org.powermock.core.MockGateway$MockInvocation.init(MockGateway.java:356)
at org.powermock.core.MockGateway$MockInvocation.<init>(MockGateway.java:307)
at org.powermock.core.MockGateway.doMethodCall(MockGateway.java:142)
at org.powermock.core.MockGateway.methodCall(MockGateway.java:125)
at org.elasticsearch.client.transport.TransportClient.buildTemplate(TransportClient.java:162)
networkModule.getTransportSupplier() returns Supplier.
here is code from networkModule: https://github.com/elastic/elasticsearch/blob/master/core/src/main/java/org/elasticsearch/common/network/NetworkModule.java
any idea why?
I think this is a bug with Powermock.
See that entry in their issues database; which shows the same stack trace (although for some different target). But close enough.
So, chances are, this will be fixed at some point. Or not.
Long story, short rant: I have seen too many such problems with PowerMock; thus I decided at some point that I rather fix my broken designs; instead of using the PowerMock hammer. In my experience, when we talk about "our own code"; then we simply create easy-to-test code; and then we do not need PowerMock any more. Seriously, that works. When you create your own classes, and you need PowerMock to test that; then you did something wrong! And as soon as you stop using PowerMock; you stop spending time on problems that have nothing to do with your product.
Anyway, your option space is:
Subscribe to that defect; and try to get some attention to it; the more people go there and give "me too", the more likely something will happen.
Look into your design and have a closer look why you need PowerMock(ito). And then decide if you would benefit from eliminating this requirement by changing your production code.

Why does $my_item->save fail with Rose::DB::Object?

I am trying to do a simple addition of data to a database table (PostgreSQL). At first, I couldn't even get a simple
$my_item = $_item_class->new(...);
to work. I discovered I had spelled a field differently in my code from what I had in my "model" code.
But, now, this is working, but when I try:
$my_item->save;
it seems an exception is thrown. All this is occurring in an eval {...} structure and I would like to catch the exception and see what is going wrong, but I don't know how to do that.
Why would something like the "save" be failing here? I have checked everything, and all seems right (of course!).
And, how do I catch the exception that seems to be being thrown?
Thank you!
I figured all this out myself. It was simple. I had duplicated a field in my class somehow when I had done an edit to it. That was all. The class just had two identically named fields specified in the hash table in the class, both with identical characteristics. When I removed one of these, the code worked.
With regard to my second question about how to catch the exception, I had to learn how to have an
if ($#) {
.
.
.
}
right after my "eval {...}" structure. Because I am new to Perl, I didn't understand that. But, it was actually pretty easy to figure out. My problem was that I was working from some code as a model for me that didn't do that but named specific exceptions that were thrown in its "eval {...}" code. So, I thought that I had to have the names of exceptions that could be thrown by Rose::DB::Object calls, but I couldn't find any such exceptions in the documentation. When I learned about "if ($#) {...}", I was able to print out the reported exception in $# and from that I was able to see the problem with the duplicate field I mentioned above.
That was all there was to it. Everything is working just fine now.

Does it make any real sense to make read-only properties out of "reference types" in an AS3 class?

Take the following code:
private var m_iQuanitity:int;
public function get quantity():int
{
return m_iQuantity;
}
That seems to make perfect sense. You can see what the quantity is from an outside class without any problems, but you can't really mess with it at all. Now take the following code:
private var m_acUsers:ArrayCollection = new ArrayCollection();
public function get users():ArrayCollection
{
return m_acUsers;
}
In that case you can't really set the variable directly, but you can still do just about everything else under the sun to it without any problems. You can call its AddItem and RemoveItemAt functions, which can do quite a bit to "set" the variable.
Does it still make sense to do this? I know you can create a duplicate ArrayCollection and just pass the duplicate back to avoid allowing it to be set, but doing stuff like that all over the place, purely for defensive programming, can waste a lot of CPU time. So I guess I'm asking if it still makes sense anyway, how so, and if I'm missing the point of using get and set completely? Thanks!
Syntactically there is nothing wrong with what you've got, but the second example does break down the concept of 'get' by making more than a read only property. If you need to adhere to a read only policy, then you've broken that since now you can manipulate the ArrayCollection.
In the end it comes down to what it is you're tying to do. Does it matter for the project that you can change the value? If you're working on a project with more than a few people, this type of coding will require you to either add a comment or have you explain what you're doing. When ever you do something outside of the norm, that can add confusion, so it's always best to simplify and stick to what is expected, avoiding having to explain something.
Also, I can think of a few ways this could cause problems - changing values outside of the function if you pass the returned property off to other classes that don't know where it came from and having internal code in the original class fail.

actionscript 3 How to access 'this' in inline function

I am trying to do something like:
String.prototype.print=function(){trace(??????)}
I can't for the life of me figure out a way to get at the string! Yes I know there are other ways to approach this etc. but...
Not sure what the problem is, using this works fine in anonymous functions.
String.prototype.print=function():String{return "printed "+this;}
var o:Object = "foo";
trace(o.print()); // traces: printed foo
I just tricked the compiler to use an object, because "foo".print() causes
Error: Call to a possibly undefined method print through a reference with static type String.
It looks like you are mixing ActionScript 2 into your ActionScript 3 code. As kapep said, using "this" will work in your example. That is, this is perfectly valid code:
String.prototype.print=function(){trace(this)}
Of course, you are missing a semi-colon but that shouldn't matter:
String.prototype.print=function(){trace(this);} //semi-colon after 'trace(this)'
Depending on your development environment, you might be having trouble viewing trace statements, in general. In Flex Builder, for example, trace statements don't show up at all unless you are in Debug mode. Insert another call to trace to verify that you can see trace statements.
As you said, there are many other ways to approach this, such as extending the String class and adding your "Print" function. If you really can't get this to work, then trying an ActionScript 3 (i.e. Object-Oriented) approach might be your best option.

What's a good naming convention for methods that take conditional action?

Let's say I have a method, Foo(). There are only certain times when Foo() is appropriate, as determined by the method ShouldFooNow(). However, there are many times when the program must consider if Foo() is appropriate at this time. So instead of writing:
if ShouldFooNow():
Foo()
everywhere, I just make that into one function:
def __name():
if ShouldFooNow():
Foo()
What would be a good name for this method? I'm having a hard time coming up with a good convention. IfNecessaryFoo() is awkward, particularly if Foo() has a longer name. DoFooIfShould()? Even more awkward.
What would be a better name style?
I think you're pretty close. Put the action/intent at the head of the method name, for easier alphabetic searching. If I were writing something like that, I'd consider
FooIfNecessary()
FooIfRequired()
Say, for instance,
ElevatePermissionsIfNecessary()
You could use EnsureFoo().
For example, the method EnsurePermissions() will take the appropriate action if needed. If the permissions are already correct, the method won't do anything.
I've recently started using the convention:
FooIf(args, bool);
Where args are any arguments that the method takes and bool is either expecting a boolean value or a Func of some kind that resolves to a boolean. Then, within that method, I check the bool and run the logic. Keeps such assertions down to one line and looks clean to me.
Example in my C# code for logging:
public void WarnIf<T>(T value, string message, Func<T, bool> isTrue)
{
if (isTrue(value)) _log.Warn(message);
}
Then I would call it with something like:
WarnIf(someObject, "This is a warning message to be logged.", s => s.SomeCondition == true);
(That caller may not be correct, but you get the idea... I don't have the code in front of me right now.)
Michael Petrotta's answer (IfNecessary or IfRequired suffix) is good, but I prefer a shorter alternative: IfNeeded.
ElevatePermissionsIfNeeded()
And if you want something even shorter I would consider a prefix like May or Might:
MayElevatePermissions()
MightElevatePermissions()
I don't see what's wrong with the original code:
if shouldFoo():
Foo();
is perfectly clear IMHO.
Not just that, but it clearly separates concerns of deciding about doing the action, vs the action itself.
Another option for a similar question with a slightly different approach to avoiding the postfix:
https://softwareengineering.stackexchange.com/a/161754/262009