LibGdx: Net.HttpResponse not "immutable" -is it reused or what? - libgdx

In libgdx, When I use Gdx.net.sendHttpRequest with a Net.HttpResponseListener is the Net.HttpResponse object only valid to read from from within the handleHttpResponse(Net.HttpResponse httpResponse) method?
I tried:
String r=httpResponse.getResultAsString();
from within handleHttpResponse(Net.HttpResponse httpResponse)
and then again from outside somewhere, else. The object was there, but
String r=httpResponse.getResultAsString();
resulted in "" this time. Is the Net.HttpResponse object reused internally or why would the result change? So I now the object is mutable, but still...it would be practical to pass it around to other places.

it's a stream; reading it once depleats it. look at the implementation. e.g. https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/net/NetJavaImpl.java#L72

Related

Are methods also objects like functions are?

I read that functions (AKA static methods) are objects (instances of the Function class). Are methods (instance functions) also objects? I can't find the answer in the official documentation. It only says functions are objects (but doesn't explain if all functions are, including methods).
It is quite easy to verify that the method is an object:
class Foo {
bar() {}
}
void main() {
print(Foo().bar is Object); // prints true
}
and linter shows a warning:
Unnecessary type check, the result is always true
Technically, the answer is "no". In practice, that never matters.
Instance methods are properties of classes that can be invoked via objects that are instances of those classes. A method is not itself a value, so it makes not sense to ask if it's an object, because all objects are values. You can refer to a method by name (it's "denotable"), but that's it. You cannot evaluate an expression to a method or store it in a variable.
However, you can tear off an instance method from an object. When you do that, a new function object is created which, when called, will invoke the method on the original object with the same arguments.
That function object is, well, both a function and an object. It is not the method itself, though, if one is being pedantic.
In practice, if you ever care to ask if something is an object, it's likely already a value, and then that thing is an object.
(Static methods are also technically not objects, but they are so close to the function object created when you tear them off, that the distinction is never practically significant. The language semantics differentiates because when you create an object, it matters which object it is - what is it equal to and identical to - and until you creates a value, the language prefers to just not have to specify that.)

Construct object on function ccall in Julia

I am trying to simplify some binding to C but I am not sure if this is even possible, what I am trying to do is pass an array and expect to receive in a function so an object can be constructed by the type specified in the parameter or by ccall calling the correct convert function and initialize a struct object.
Previous code, the bindings are full of Vector3(v...) and Color(c...), is there a way to avoid this be automatic handling?
drawline(startPos, endPos, color) = ccall((:DrawLine3D, "my_lib"), Cvoid, (Vector3,Vector3,Color), Vector3(startPos...), Vector3(endPos...), Color(color...))
drawpoint([10,10,10],[100,100,100],[155,155,155,255]) # call example
Is it possible to reduce the code with something like this?:
struct Vector3
x::Cfloat
y::Cfloat
z::Cfloat
Vector3((x,y,z))=new(x,y,z)
end
#first attempt
#trying to call the Vector3 constructor without calling explicitly
drawpoint(startpos::Vector3,endpos::Vector3,color::Color) = ccall((:DrawPoint3D, "my_lib"), Cvoid, (Vector3,Vector3,Color), startpos,endpos,color)
#second attempt (should be the simplest way to go)
#trying to receive arrays so ccall can convert from list or tuple to Struct object
drawpoint(startpos,endpos,color) = ccall((:DrawPoint3D, "my_lib"), Cvoid, (Vector3,Vector3,Color), startpos,endpos,color)
Is something like this even possible in Julia?
You just need to define the appropriate conversion. ccall will call this for you. I think this should do it:
Base.convert(::Type{Vector3}, x::AbstractVector) = Vector3(x)
You'll probably want to add some length checks and such, and I'd probably recommend using tuples or StaticArrays instead of Vectors for efficiency's sake.

Actionscript: Why does this Event Listener cause massive memory consumption

I have an array of buttons and I attached event listeners like this.
arr[c].addEventListener(MouseEvent.MOUSE_UP, Proxy.go(this, click, Model.categoriesListXml.category_0[i].category_1[j].#category_id, Model.categoriesListXml.category_0[i].category_1[j].#name));
150 of these used 32MB of memory.
When I used the following memory dropped to 2MB.
var categoryId:String = Model.categoriesListXml.category_0[i].category_1[j].#category_id;
var name:String = Model.categoriesListXml.category_0[i].category_1[j].#name;
arr[c].addEventListener(MouseEvent.MOUSE_UP, Proxy.go(this, click, categoryId, name));
All I did was put the xml elements their own vars before using in the event listener.
Does anyone know why this is happening?
My guess is that the entire XML object gets included rather than just the elements I need.
I think it works as the following.
Try. Flash is very lazy when it comes to disposing anything XML-related. So lazy, in fact, that it even has System.disposeXML(...) method because otherwise an XML object might not be garbage collected even if you consciously remove every single reference to it.
Catch. It is important to understand, that most XML operations result in XML or XMLList object, say
// XML source.
var X:XML = <root a="1" />;
// You might think it returns String, but no, it is just autocast to String.
var a:String = X.#a;
// If you don't specify data type, this returns XMLList object of length 1,
// with an XML member of type "attribute", name "a" (or maybe "#a"), and so on.
var A:* = X.#a;
So, without explicitly casting your attribute to String you pass 2 XMLList objects as the function arguments instead (or so it seems).
Finally. Just looking at Proxy.go(...) tells us that it creates a delegate (which is a type of closure), an unnamed unbound function with the stored arguments list. It should look similar to this:
public function go(target:Object, method:Function, ...rest:Array):Function
{
return function():void
{
method.apply(target, rest);
}
}
This works due to ECMA standard (probably works with JavaScript as well) that allows closures to access all their parent method data: local variables and method arguments.
So, you have it. Some unnamed function keeps (pretty much forever) somewhere in the player's memory a list of untyped arguments, which contains your XMLList objects (which are persistent and not easily disposed of). Then you create 150 such monstrosities this way. It's only natural that memory leaks in fountains and niagaras.

static methods that return an instance of an object but behave like a constructor

So I have an object that can be constructed in a few ways. The constructors have signatures like, the one that loads an object from a file:
Object::Object( string filenameToLoadFrom ) ;
And how it behaves is pretty straightforward.
Object( "filename.dat" ) ; // loads object from filename
The constructor signature pretty much says what it does, although a static method Load might arguably be better:
static Object* Object::Load( string filenameToLoadFrom ) ;
(syntax above is slightly incorrect but you get the idea.)
Then we come into cases where what the constructor does isn't immediately obvious from the parameters. a name is needed to make it clear from the API what the constructor does.
The question is, is it a good idea to write static methods that return an instance of the object, just for the sake of being able to name the constructor?
This is actually considered a common secondary benefit of the Factory Method Pattern. It is potentially useful in specific scenarios, especially for things where you have the same argument type providing very different meanings.
For example, it's not uncommon to have a class representing an "Angle" which can be constructed by a single floating point number which could represent degrees or radians. Constructors do not provide enough context (or a clean way) to implement this, where a "factory method" makes this very clear.
I believe it's a good idea especially if you need more than one constructor that both take the same type of parameter(s). For example: static Object* loadFromFile( String fileName) and statc Object* loadFromResorce(String resourceName). You can even make the actual constructor private to enforce the use of the static constructors.

Function Parameter best practice

I have question regarding the use of function parameters.
In the past I have always written my code such that all information needed by a function is passed in as a parameter. I.e. global parameters are not used.
However through looking over other peoples code, functions without parameters seem to be the norm. I should note that these are for private functions of a class and that the values that would have been passed in as paramaters are in fact private member variables for that class.
This leads to neater looking code and im starting to lean towards this for private functions but would like other peoples views.
E.g.
Start();
Process();
Stop();
is neater and more readable than:
ParamD = Start(paramA, ParamB, ParamC);
Process(ParamA, ParamD);
Stop(ParamC);
It does break encapsulation from a method point of view but not from a class point of view.
There's nothing wrong in principle with having functions access object fields, but the particular example you give scares me, because the price of simplifying your function calls is that you're obfuscating the life cycle of your data.
To translate your args example into fields, you'd have something like:
void Start() {
// read FieldA, FieldB, and FieldC
// set the value of FieldD
}
void Process() {
// read FieldA and do something
// read FieldD and do something
}
void Stop() {
// read the value of FieldC
}
Start() sets FieldD by side effect. This means that it's probably not valid to call Process() until after you've called Start(). But the code doesn't tell you that. You only find out by searching to see where FieldD is initialized. This is asking for bugs.
My rule of thumb is that functions should only access an object field if it's always safe to access that field. Best if it's a field that's initialized at construction time, but a field that stores a reference to a collaborator object or something, which could change over time, is okay too.
But if it's not valid to call one function except after another function has produced some output, that output should be passed in, not stored in the state. If you treat each function as independent, and avoid side effects, your code will be more maintainable and easier to understand.
As you mentioned, there's a trade-off between them. There's no hard rule for always preferring one to another. Minimizing the scope of variables will keep their side effect local, the code more modular and reusable and debugging easier. However, it can be an overkill in some cases. If you keep your classes small (which you should do) then the shared variable would generally make sense. However, there can be other issues such as thread safety that might affect your choice.
Not passing the object's own member attributes as parameters to its methods is the normal practice: effectively when you call myobject.someMethod() you are implicitly passing the whole object (with all its attributes) as a parameter to the method code.
I generally agree with both of Mehrdad and Mufasa's comments. There's no hard and fast rule for what is best. You should use the approach that suits the specific scenarios you work on bearing in mind:
readability of code
cleanliness of code (can get messy if you pass a million and one parameters into a method - especially if they are class level variables. Alternative is to encapsulate parameters into groups, and create e.g. a struct to whole multiple values, in one object)
testability of code. This is important in my opinion. I have occassionally refactored code to add parameters to a method purely for the purpose of improving testability as it can allow for better unit testing
This is something you need to measure on a case by case basis.
For example ask yourself if you were to use parameter in a private method is it ever going to be reasonable to pass a value that is anything other than that of a specific property in the object? If not then you may as well access the property/field directly in the method.
OTH you may ask yourself does this method mutate the state of the object? If not then perhaps it may be better as a Static and have all its required values passed as parameters.
There are all sorts of considerations, the upper most has to be "What is most understandable to other developers".
In an object-oriented language it is common to pass in dependencies (classes that this class will communicate with) and configuration values in the constructor and only the values to actually be operated on in the function call.
This can actually be more readable. Consider code where you have a service that generates and publishes an invoice. There can be a variety of ways to do the publication - via a web-service that sends it to some sort of centralized server, or via an email sent to someone in the warehouse, or maybe just by sending it to the default printer. However, it is usually simpler for the method calling Publish() to not know the specifics of how the publication is happening - it just needs to know that the publication went off without a hitch. This allows you to think of less things at a time and concentrate on the problem better. Then you are simply making use of an interface to a service (in C#):
// Notice the consuming class needs only know what it does, not how it does it
public interface IInvoicePublisher {
pubic void Publish(Invoice anInvoice);
}
This could be implemented in a variety of ways, for example:
public class DefaultPrinterInvoicePublisher
DefaultPrinterInvoicePublisher _printer;
public DefaultPrinterInvoicePublisher(DefaultPrinterFacade printer) {
_printer = printer
}
public void Publish(Invoice anInvoice) {
printableObject = //Generate crystal report, or something else that can be printed
_printer.Print(printableObject);
}
The code that uses it would then take an IInvoicePublisher as a constructor parameter too so that functionality is available to be used throughout.
Generally, it's better to use parameters. Greatly increases the ability to use patterns like dependency injection and test-driven design.
If it is an internal only method though, that's not as important.
I don't pass the object's state to the private methods because the method can access the state just like that.
I pass parameters to a private method when the private method is invoked from a public method and the public method gets a parameter which it then sends to the private method.
Public DoTask( string jobid, object T)
{
DoTask1(jobid, t);
DoTask2(jobid, t);
}
private DoTask1( string jobid, object T)
{
}
private DoTask2( string jobid, object T)
{
}