Writing JQuery-Style Function Chains in AS3 and Other Class-Based Languages

This is not a specific problem I can do, but I believe the question is relevant to SO as there might be a "correct" OO answer as well as efficiency / loss of performance doing this. I'm working in AS3, but I believe this question will be relevant for other / oo class based languages.

I was trying to figure out how to use multiple Java type constructors for a class with different parameters (this is another story), but it got me thinking about jQuery and how it binds functions when, if possible, return their object to which they are turning.

It doesn't always do for clean code with jQuery, and I assume this is the classic approach, but I thought about , if something needs to be said for this method:

//execute chains of methods on creation, as each returns its parent class (person)
var person:Person = new Person().male('a male', 25).wakeUp().lookAround();

//Or later
person.getUp().rubEyes();

      

... and are there member functions returning an object that is often unnecessary present a significant waste / performance issue?

This seems to be a good way to keep the code and also present the function sequences in a more readable way, I wondered if anyone could help.

Thank you in advance

+3


source to share


1 answer


Yes, there is something to be said for person.getUp().rubEyes()

: semantically it looks better. It's all.

new Person().male('a male', 25)

- this is a completely different case. Man is not a verb like getUp. I would prefer: new Person({ gender: 'male', age: 25})

.



Is there a significant performance improvement when the returned object is not being used? Not. First of all, most (jit) compilers are smart enough to understand that the returned object is never used and therefore won't execute those instructions at all. This is an optimization strategy called elimination of dead code. Second, even if the compiler does not perform this optimization, we are still talking about a few unwanted clock cycles. There is nothing to worry about. In general, I would advise you not to worry about these performance issues at all. Better to focus your optimization efforts on the parts of your code that the compiler can't help you (like design, algorithms, etc.).

Have fun with the chain!

+2


source







All Articles