1
0
Fork 0
easejs/test/MemberBuilder/MethodTest.js

331 lines
10 KiB
JavaScript
Raw Normal View History

/**
* Tests method builder
*
2014-03-15 23:52:06 -04:00
* Copyright (C) 2010, 2011, 2012, 2013, 2014 Mike Gerwitz
*
* This file is part of GNU ease.js.
*
* ease.js is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
var shared = require( __dirname + '/inc-common' );
[#25] Finished refactoring MemberBuilder/MethodTest and removed inc-member_builder-common (no longer needed) Finally feels like things are starting to come together. It's rather interesting looking back. Each time I begin writing a piece of software, I think to myself, "This is the best way to do it." Well, generally. Perhaps the implementation could have been better, but I may not have had the time. However, the general concept remains. Each time I look back months later and find that I disagree with certain decisions. I find certain implementations to be messy or poorly constructed. Or perhaps I was just being lazy to begin with. Whatever the case, it is comforting. It shows that one is continuing to learn and evolve. Now, in the case of ease.js, we're working with a number of different factors in regards to my perception of prior code quality. Primarily, I'm looking at a basic implementation (in this case, I'm referring to test cases) that served as a foundation that could be later evolved. I didn't have the time to devote to a stronger solution. However, since the project has evolved so far past my original expectations, a more sophisticated solution is needed in order to simplify the overall design. That is what happened here. Of course, we're also looking at a year's worth of additional, intimate experience with a language. Regardless of the reason, I love to see software evolve. Especially my own. It's as if I'm watching my child grow. From that, I can get a great deal of satisfaction. One shouldn't expect perfection. But one should certainly aim for it.
2011-10-26 23:38:43 -04:00
require( 'common' ).testCase(
{
caseSetUp: function()
{
var _self = this;
this.testArgs = function( args, name, value, keywords, state )
{
shared.testArgs( _self, args, name, value, keywords, state,
function(
prev_default, pval_given, pkey_given
)
{
var expected = _self.members[ 'public' ][ name ];
if ( !expected )
{
return prev_default;
}
return {
value: {
expected: expected,
given: pval_given.member,
},
keywords: {
expected: expected.___$$keywords$$, // XXX
given: pkey_given,
},
};
}
);
};
// simply intended to execute test two two perspectives
this.weakab = [
];
},
[#25] Finished refactoring MemberBuilder/MethodTest and removed inc-member_builder-common (no longer needed) Finally feels like things are starting to come together. It's rather interesting looking back. Each time I begin writing a piece of software, I think to myself, "This is the best way to do it." Well, generally. Perhaps the implementation could have been better, but I may not have had the time. However, the general concept remains. Each time I look back months later and find that I disagree with certain decisions. I find certain implementations to be messy or poorly constructed. Or perhaps I was just being lazy to begin with. Whatever the case, it is comforting. It shows that one is continuing to learn and evolve. Now, in the case of ease.js, we're working with a number of different factors in regards to my perception of prior code quality. Primarily, I'm looking at a basic implementation (in this case, I'm referring to test cases) that served as a foundation that could be later evolved. I didn't have the time to devote to a stronger solution. However, since the project has evolved so far past my original expectations, a more sophisticated solution is needed in order to simplify the overall design. That is what happened here. Of course, we're also looking at a year's worth of additional, intimate experience with a language. Regardless of the reason, I love to see software evolve. Especially my own. It's as if I'm watching my child grow. From that, I can get a great deal of satisfaction. One shouldn't expect perfection. But one should certainly aim for it.
2011-10-26 23:38:43 -04:00
setUp: function()
{
Added `proxy' keyword support The concept of proxy methods will become an important, core concept in ease.js that will provide strong benefits for creating decorators and proxies, removing boilerplate code and providing useful metadata to the system. Consider the following example: Class( 'Foo', { // ... 'public performOperation': function( bar ) { this._doSomethingWith( bar ); return this; }, } ); Class( 'FooDecorator', { 'private _foo': null, // ... 'public performOperation': function( bar ) { return this._foo.performOperation( bar ); }, } ); In the above example, `FooDecorator` is a decorator for `Foo`. Assume that the `getValueOf()` method is undecorated and simply needs to be proxied to its component --- an instance of `Foo`. (It is not uncommon that a decorator, proxy, or related class will alter certain functionality while leaving much of it unchanged.) In order to do so, we can use this generic, boilerplate code return this.obj.func.apply( this.obj, arguments ); which would need to be repeated again and again for *each method that needs to be proxied*. We also have another problem --- `Foo.getValueOf()` returns *itself*, which `FooDecorator` *also* returns. This breaks encapsulation, so we instead need to return ourself: 'public performOperation': function( bar ) { this._foo.performOperation( bar ); return this; }, Our boilerplate code then becomes: var ret = this.obj.func.apply( this.obj, arguments ); return ( ret === this.obj ) ? this : ret; Alternatively, we could use the `proxy' keyword: Class( 'FooDecorator2', { 'private _foo': null, // ... 'public proxy performOperation': '_foo', } ); `FooDecorator2.getValueOf()` and `FooDecorator.getValueOf()` both perform the exact same task --- proxy the entire call to another object and return its result, unless the result is the component, in which case the decorator itself is returned. Proxies, as of this commit, accomplish the following: - All arguments are forwarded to the destination - The return value is forwarded to the caller - If the destination returns a reference to itself, it will be replaced with a reference to the caller's context (`this`). - If the call is expected to fail, either because the destination is not an object or because the requested method is not a function, a useful error will be immediately thrown (rather than the potentially cryptic one that would otherwise result, requiring analysis of the stack trace). N.B. As of this commit, static proxies do not yet function properly.
2012-05-02 13:26:47 -04:00
var _self = this;
[#25] Finished refactoring MemberBuilder/MethodTest and removed inc-member_builder-common (no longer needed) Finally feels like things are starting to come together. It's rather interesting looking back. Each time I begin writing a piece of software, I think to myself, "This is the best way to do it." Well, generally. Perhaps the implementation could have been better, but I may not have had the time. However, the general concept remains. Each time I look back months later and find that I disagree with certain decisions. I find certain implementations to be messy or poorly constructed. Or perhaps I was just being lazy to begin with. Whatever the case, it is comforting. It shows that one is continuing to learn and evolve. Now, in the case of ease.js, we're working with a number of different factors in regards to my perception of prior code quality. Primarily, I'm looking at a basic implementation (in this case, I'm referring to test cases) that served as a foundation that could be later evolved. I didn't have the time to devote to a stronger solution. However, since the project has evolved so far past my original expectations, a more sophisticated solution is needed in order to simplify the overall design. That is what happened here. Of course, we're also looking at a year's worth of additional, intimate experience with a language. Regardless of the reason, I love to see software evolve. Especially my own. It's as if I'm watching my child grow. From that, I can get a great deal of satisfaction. One shouldn't expect perfection. But one should certainly aim for it.
2011-10-26 23:38:43 -04:00
// stub factories used for testing
var stubFactory = this.require( 'MethodWrapperFactory' )(
Private methods are no longer wrapped This is an exciting performance optimization that seems to have eluded me for a surprisingly long time, given that the realization was quite random. ease.js accomplishes much of its work through a method wrapper---each and every method definition (well, until now) was wrapped in a closure that performed a number of steps, depending on the type of wrapper involved: 1. All wrappers perform a context lookup, binding to the instance's private member object of the class that defined that particular method. (See "Implementation Details" in the manual for more information.) 2. This context is restored upon returning from the call: if a method returns `this', it is instead converted back to the context in which the method was invoked, which prevents the private member object from leaking out of a public interface. 3. In the event of an override, this.__super is set up (and torn down). There are other details (e.g. the method wrapper used for method proxies), but for the sake of this particular commit, those are the only ones that really matter. There are a couple of important details to notice: - Private members are only ever accessible from within the context of the private member object, which is always the context when executing a method. - Private methods cannot be overridden, as they cannot be inherited. Consequently: 1. We do not need to perform a context lookup: we are already in the proper context. 2. We do not need to restore the context, as we never needed to change it to begin with. 3. this.__super is never applicable. Method wrappers are therefore never necessary for private methods; they have therefore been removed. This has some interesting performance implications. While in most cases the overhead of method wrapping is not a bottleneck, it can have a strong impact in the event of frequent method calls or heavily recursive algorithms. There was one particular problem that ease.js suffered from, which is mentioned in the manual: recursive calls to methods in ease.js were not recommended because it (a) made two function calls for each method call, effectively halving the remaining call stack size, and (b) tail call optimization could not be performed, because recursion invoked the wrapper, *not* the function that was wrapped. By removing the method wrapper on private methods, we solve both of these problems; now, heavily recursive algorithms need only use private methods (which could always be exposed through a protected or public API) when recursing to entirely avoid any performance penalty by using ease.js. Running the test cases on my system (your results may vary) before and after the patch, we have: BEFORE: 0.170s (x1000 = 0.0001700000s each): Declare 1000 anonymous classes with private members 0.021s (x500000 = 0.0000000420s each): Invoke private methods internally AFTER: 0.151s (x1000 = 0.0001510000s each): Declare 1000 anonymous classes with private members 0.004s (x500000 = 0.0000000080s each): Invoke private methods internally This is all the more motivation to use private members, which enforces encapsulation; keep in mind that, because use of private members is the ideal in well-encapsulated and well-factored code, ease.js has been designed to perform best under those circumstances.
2014-03-20 22:36:43 -04:00
function( func )
{
// still wrap it so that the function is encapsulated
return function() { return func() };
}
[#25] Finished refactoring MemberBuilder/MethodTest and removed inc-member_builder-common (no longer needed) Finally feels like things are starting to come together. It's rather interesting looking back. Each time I begin writing a piece of software, I think to myself, "This is the best way to do it." Well, generally. Perhaps the implementation could have been better, but I may not have had the time. However, the general concept remains. Each time I look back months later and find that I disagree with certain decisions. I find certain implementations to be messy or poorly constructed. Or perhaps I was just being lazy to begin with. Whatever the case, it is comforting. It shows that one is continuing to learn and evolve. Now, in the case of ease.js, we're working with a number of different factors in regards to my perception of prior code quality. Primarily, I'm looking at a basic implementation (in this case, I'm referring to test cases) that served as a foundation that could be later evolved. I didn't have the time to devote to a stronger solution. However, since the project has evolved so far past my original expectations, a more sophisticated solution is needed in order to simplify the overall design. That is what happened here. Of course, we're also looking at a year's worth of additional, intimate experience with a language. Regardless of the reason, I love to see software evolve. Especially my own. It's as if I'm watching my child grow. From that, I can get a great deal of satisfaction. One shouldn't expect perfection. But one should certainly aim for it.
2011-10-26 23:38:43 -04:00
);
Added `proxy' keyword support The concept of proxy methods will become an important, core concept in ease.js that will provide strong benefits for creating decorators and proxies, removing boilerplate code and providing useful metadata to the system. Consider the following example: Class( 'Foo', { // ... 'public performOperation': function( bar ) { this._doSomethingWith( bar ); return this; }, } ); Class( 'FooDecorator', { 'private _foo': null, // ... 'public performOperation': function( bar ) { return this._foo.performOperation( bar ); }, } ); In the above example, `FooDecorator` is a decorator for `Foo`. Assume that the `getValueOf()` method is undecorated and simply needs to be proxied to its component --- an instance of `Foo`. (It is not uncommon that a decorator, proxy, or related class will alter certain functionality while leaving much of it unchanged.) In order to do so, we can use this generic, boilerplate code return this.obj.func.apply( this.obj, arguments ); which would need to be repeated again and again for *each method that needs to be proxied*. We also have another problem --- `Foo.getValueOf()` returns *itself*, which `FooDecorator` *also* returns. This breaks encapsulation, so we instead need to return ourself: 'public performOperation': function( bar ) { this._foo.performOperation( bar ); return this; }, Our boilerplate code then becomes: var ret = this.obj.func.apply( this.obj, arguments ); return ( ret === this.obj ) ? this : ret; Alternatively, we could use the `proxy' keyword: Class( 'FooDecorator2', { 'private _foo': null, // ... 'public proxy performOperation': '_foo', } ); `FooDecorator2.getValueOf()` and `FooDecorator.getValueOf()` both perform the exact same task --- proxy the entire call to another object and return its result, unless the result is the component, in which case the decorator itself is returned. Proxies, as of this commit, accomplish the following: - All arguments are forwarded to the destination - The return value is forwarded to the caller - If the destination returns a reference to itself, it will be replaced with a reference to the caller's context (`this`). - If the call is expected to fail, either because the destination is not an object or because the requested method is not a function, a useful error will be immediately thrown (rather than the potentially cryptic one that would otherwise result, requiring analysis of the stack trace). N.B. As of this commit, static proxies do not yet function properly.
2012-05-02 13:26:47 -04:00
// used for testing proxies explicitly
var stubProxyFactory = this.require( 'MethodWrapperFactory' )(
function()
{
_self.proxyFactoryCall = arguments;
return _self.proxyReturnValue;
}
);
this.proxyFactoryCall = null;
this.proxyReturnValue = function() {};
[#25] Finished refactoring MemberBuilder/MethodTest and removed inc-member_builder-common (no longer needed) Finally feels like things are starting to come together. It's rather interesting looking back. Each time I begin writing a piece of software, I think to myself, "This is the best way to do it." Well, generally. Perhaps the implementation could have been better, but I may not have had the time. However, the general concept remains. Each time I look back months later and find that I disagree with certain decisions. I find certain implementations to be messy or poorly constructed. Or perhaps I was just being lazy to begin with. Whatever the case, it is comforting. It shows that one is continuing to learn and evolve. Now, in the case of ease.js, we're working with a number of different factors in regards to my perception of prior code quality. Primarily, I'm looking at a basic implementation (in this case, I'm referring to test cases) that served as a foundation that could be later evolved. I didn't have the time to devote to a stronger solution. However, since the project has evolved so far past my original expectations, a more sophisticated solution is needed in order to simplify the overall design. That is what happened here. Of course, we're also looking at a year's worth of additional, intimate experience with a language. Regardless of the reason, I love to see software evolve. Especially my own. It's as if I'm watching my child grow. From that, I can get a great deal of satisfaction. One shouldn't expect perfection. But one should certainly aim for it.
2011-10-26 23:38:43 -04:00
this.sut = this.require( 'MemberBuilder' )(
Added `proxy' keyword support The concept of proxy methods will become an important, core concept in ease.js that will provide strong benefits for creating decorators and proxies, removing boilerplate code and providing useful metadata to the system. Consider the following example: Class( 'Foo', { // ... 'public performOperation': function( bar ) { this._doSomethingWith( bar ); return this; }, } ); Class( 'FooDecorator', { 'private _foo': null, // ... 'public performOperation': function( bar ) { return this._foo.performOperation( bar ); }, } ); In the above example, `FooDecorator` is a decorator for `Foo`. Assume that the `getValueOf()` method is undecorated and simply needs to be proxied to its component --- an instance of `Foo`. (It is not uncommon that a decorator, proxy, or related class will alter certain functionality while leaving much of it unchanged.) In order to do so, we can use this generic, boilerplate code return this.obj.func.apply( this.obj, arguments ); which would need to be repeated again and again for *each method that needs to be proxied*. We also have another problem --- `Foo.getValueOf()` returns *itself*, which `FooDecorator` *also* returns. This breaks encapsulation, so we instead need to return ourself: 'public performOperation': function( bar ) { this._foo.performOperation( bar ); return this; }, Our boilerplate code then becomes: var ret = this.obj.func.apply( this.obj, arguments ); return ( ret === this.obj ) ? this : ret; Alternatively, we could use the `proxy' keyword: Class( 'FooDecorator2', { 'private _foo': null, // ... 'public proxy performOperation': '_foo', } ); `FooDecorator2.getValueOf()` and `FooDecorator.getValueOf()` both perform the exact same task --- proxy the entire call to another object and return its result, unless the result is the component, in which case the decorator itself is returned. Proxies, as of this commit, accomplish the following: - All arguments are forwarded to the destination - The return value is forwarded to the caller - If the destination returns a reference to itself, it will be replaced with a reference to the caller's context (`this`). - If the call is expected to fail, either because the destination is not an object or because the requested method is not a function, a useful error will be immediately thrown (rather than the potentially cryptic one that would otherwise result, requiring analysis of the stack trace). N.B. As of this commit, static proxies do not yet function properly.
2012-05-02 13:26:47 -04:00
stubFactory, stubFactory, stubProxyFactory,
this.mockValidate = this.getMock( 'MemberBuilderValidator' )
[#25] Finished refactoring MemberBuilder/MethodTest and removed inc-member_builder-common (no longer needed) Finally feels like things are starting to come together. It's rather interesting looking back. Each time I begin writing a piece of software, I think to myself, "This is the best way to do it." Well, generally. Perhaps the implementation could have been better, but I may not have had the time. However, the general concept remains. Each time I look back months later and find that I disagree with certain decisions. I find certain implementations to be messy or poorly constructed. Or perhaps I was just being lazy to begin with. Whatever the case, it is comforting. It shows that one is continuing to learn and evolve. Now, in the case of ease.js, we're working with a number of different factors in regards to my perception of prior code quality. Primarily, I'm looking at a basic implementation (in this case, I'm referring to test cases) that served as a foundation that could be later evolved. I didn't have the time to devote to a stronger solution. However, since the project has evolved so far past my original expectations, a more sophisticated solution is needed in order to simplify the overall design. That is what happened here. Of course, we're also looking at a year's worth of additional, intimate experience with a language. Regardless of the reason, I love to see software evolve. Especially my own. It's as if I'm watching my child grow. From that, I can get a great deal of satisfaction. One shouldn't expect perfection. But one should certainly aim for it.
2011-10-26 23:38:43 -04:00
);
[#25] Finished refactoring MemberBuilder/MethodTest and removed inc-member_builder-common (no longer needed) Finally feels like things are starting to come together. It's rather interesting looking back. Each time I begin writing a piece of software, I think to myself, "This is the best way to do it." Well, generally. Perhaps the implementation could have been better, but I may not have had the time. However, the general concept remains. Each time I look back months later and find that I disagree with certain decisions. I find certain implementations to be messy or poorly constructed. Or perhaps I was just being lazy to begin with. Whatever the case, it is comforting. It shows that one is continuing to learn and evolve. Now, in the case of ease.js, we're working with a number of different factors in regards to my perception of prior code quality. Primarily, I'm looking at a basic implementation (in this case, I'm referring to test cases) that served as a foundation that could be later evolved. I didn't have the time to devote to a stronger solution. However, since the project has evolved so far past my original expectations, a more sophisticated solution is needed in order to simplify the overall design. That is what happened here. Of course, we're also looking at a year's worth of additional, intimate experience with a language. Regardless of the reason, I love to see software evolve. Especially my own. It's as if I'm watching my child grow. From that, I can get a great deal of satisfaction. One shouldn't expect perfection. But one should certainly aim for it.
2011-10-26 23:38:43 -04:00
this.members = this.sut.initMembers();
},
/**
* The validator can only do its job if we're providing it with the correct
* information
*/
'Passes proper data to validator when not overriding': function()
{
var _self = this,
called = false,
name = 'foo',
value = function() {},
state = {},
keywords = {}
;
this.mockValidate.validateMethod = function()
{
called = true;
_self.testArgs( arguments, name, value, keywords, state );
};
this.assertOk( this.sut.buildMethod(
this.members, {}, name, value, keywords, function() {}, 1, {},
state
) );
this.assertEqual( true, called, 'validateMethod() was not called' );
},
'Passes proper data to validator when overriding': function()
{
var _self = this,
called = false,
name = 'foo',
value = function() {},
keywords = { 'override': true }
;
// since we're overriding
( this.members[ 'public' ].foo = function() {} ).___$$keywords$$ =
{ 'public': true };
this.mockValidate.validateMethod = function()
{
called = true;
_self.testArgs( arguments, name, value, keywords );
};
this.assertOk( this.sut.buildMethod(
this.members, {}, name, value, keywords, function() {}, 1, {}
) );
this.assertEqual( true, called, 'validateMethod() was not called' );
},
Added `proxy' keyword support The concept of proxy methods will become an important, core concept in ease.js that will provide strong benefits for creating decorators and proxies, removing boilerplate code and providing useful metadata to the system. Consider the following example: Class( 'Foo', { // ... 'public performOperation': function( bar ) { this._doSomethingWith( bar ); return this; }, } ); Class( 'FooDecorator', { 'private _foo': null, // ... 'public performOperation': function( bar ) { return this._foo.performOperation( bar ); }, } ); In the above example, `FooDecorator` is a decorator for `Foo`. Assume that the `getValueOf()` method is undecorated and simply needs to be proxied to its component --- an instance of `Foo`. (It is not uncommon that a decorator, proxy, or related class will alter certain functionality while leaving much of it unchanged.) In order to do so, we can use this generic, boilerplate code return this.obj.func.apply( this.obj, arguments ); which would need to be repeated again and again for *each method that needs to be proxied*. We also have another problem --- `Foo.getValueOf()` returns *itself*, which `FooDecorator` *also* returns. This breaks encapsulation, so we instead need to return ourself: 'public performOperation': function( bar ) { this._foo.performOperation( bar ); return this; }, Our boilerplate code then becomes: var ret = this.obj.func.apply( this.obj, arguments ); return ( ret === this.obj ) ? this : ret; Alternatively, we could use the `proxy' keyword: Class( 'FooDecorator2', { 'private _foo': null, // ... 'public proxy performOperation': '_foo', } ); `FooDecorator2.getValueOf()` and `FooDecorator.getValueOf()` both perform the exact same task --- proxy the entire call to another object and return its result, unless the result is the component, in which case the decorator itself is returned. Proxies, as of this commit, accomplish the following: - All arguments are forwarded to the destination - The return value is forwarded to the caller - If the destination returns a reference to itself, it will be replaced with a reference to the caller's context (`this`). - If the call is expected to fail, either because the destination is not an object or because the requested method is not a function, a useful error will be immediately thrown (rather than the potentially cryptic one that would otherwise result, requiring analysis of the stack trace). N.B. As of this commit, static proxies do not yet function properly.
2012-05-02 13:26:47 -04:00
/**
* The `proxy' keyword should result in a method that proxies to the given
* object's method (both identified by name).
*/
"Creates proxy when `proxy' keyword is given": function()
{
var _self = this,
called = false,
cid = 1,
name = 'foo',
value = 'bar',
keywords = { 'proxy': true },
instCallback = function() {}
;
// build the proxy
this.assertOk( this.sut.buildMethod(
Added `proxy' keyword support The concept of proxy methods will become an important, core concept in ease.js that will provide strong benefits for creating decorators and proxies, removing boilerplate code and providing useful metadata to the system. Consider the following example: Class( 'Foo', { // ... 'public performOperation': function( bar ) { this._doSomethingWith( bar ); return this; }, } ); Class( 'FooDecorator', { 'private _foo': null, // ... 'public performOperation': function( bar ) { return this._foo.performOperation( bar ); }, } ); In the above example, `FooDecorator` is a decorator for `Foo`. Assume that the `getValueOf()` method is undecorated and simply needs to be proxied to its component --- an instance of `Foo`. (It is not uncommon that a decorator, proxy, or related class will alter certain functionality while leaving much of it unchanged.) In order to do so, we can use this generic, boilerplate code return this.obj.func.apply( this.obj, arguments ); which would need to be repeated again and again for *each method that needs to be proxied*. We also have another problem --- `Foo.getValueOf()` returns *itself*, which `FooDecorator` *also* returns. This breaks encapsulation, so we instead need to return ourself: 'public performOperation': function( bar ) { this._foo.performOperation( bar ); return this; }, Our boilerplate code then becomes: var ret = this.obj.func.apply( this.obj, arguments ); return ( ret === this.obj ) ? this : ret; Alternatively, we could use the `proxy' keyword: Class( 'FooDecorator2', { 'private _foo': null, // ... 'public proxy performOperation': '_foo', } ); `FooDecorator2.getValueOf()` and `FooDecorator.getValueOf()` both perform the exact same task --- proxy the entire call to another object and return its result, unless the result is the component, in which case the decorator itself is returned. Proxies, as of this commit, accomplish the following: - All arguments are forwarded to the destination - The return value is forwarded to the caller - If the destination returns a reference to itself, it will be replaced with a reference to the caller's context (`this`). - If the call is expected to fail, either because the destination is not an object or because the requested method is not a function, a useful error will be immediately thrown (rather than the potentially cryptic one that would otherwise result, requiring analysis of the stack trace). N.B. As of this commit, static proxies do not yet function properly.
2012-05-02 13:26:47 -04:00
this.members, {}, name, value, keywords, instCallback, cid, {}
) );
Added `proxy' keyword support The concept of proxy methods will become an important, core concept in ease.js that will provide strong benefits for creating decorators and proxies, removing boilerplate code and providing useful metadata to the system. Consider the following example: Class( 'Foo', { // ... 'public performOperation': function( bar ) { this._doSomethingWith( bar ); return this; }, } ); Class( 'FooDecorator', { 'private _foo': null, // ... 'public performOperation': function( bar ) { return this._foo.performOperation( bar ); }, } ); In the above example, `FooDecorator` is a decorator for `Foo`. Assume that the `getValueOf()` method is undecorated and simply needs to be proxied to its component --- an instance of `Foo`. (It is not uncommon that a decorator, proxy, or related class will alter certain functionality while leaving much of it unchanged.) In order to do so, we can use this generic, boilerplate code return this.obj.func.apply( this.obj, arguments ); which would need to be repeated again and again for *each method that needs to be proxied*. We also have another problem --- `Foo.getValueOf()` returns *itself*, which `FooDecorator` *also* returns. This breaks encapsulation, so we instead need to return ourself: 'public performOperation': function( bar ) { this._foo.performOperation( bar ); return this; }, Our boilerplate code then becomes: var ret = this.obj.func.apply( this.obj, arguments ); return ( ret === this.obj ) ? this : ret; Alternatively, we could use the `proxy' keyword: Class( 'FooDecorator2', { 'private _foo': null, // ... 'public proxy performOperation': '_foo', } ); `FooDecorator2.getValueOf()` and `FooDecorator.getValueOf()` both perform the exact same task --- proxy the entire call to another object and return its result, unless the result is the component, in which case the decorator itself is returned. Proxies, as of this commit, accomplish the following: - All arguments are forwarded to the destination - The return value is forwarded to the caller - If the destination returns a reference to itself, it will be replaced with a reference to the caller's context (`this`). - If the call is expected to fail, either because the destination is not an object or because the requested method is not a function, a useful error will be immediately thrown (rather than the potentially cryptic one that would otherwise result, requiring analysis of the stack trace). N.B. As of this commit, static proxies do not yet function properly.
2012-05-02 13:26:47 -04:00
this.assertNotEqual( null, this.proxyFactoryCall,
"Proxy factory should be used when `proxy' keyword is provided"
);
this.assertDeepEqual(
[ value, null, cid, instCallback, name, keywords ],
Added `proxy' keyword support The concept of proxy methods will become an important, core concept in ease.js that will provide strong benefits for creating decorators and proxies, removing boilerplate code and providing useful metadata to the system. Consider the following example: Class( 'Foo', { // ... 'public performOperation': function( bar ) { this._doSomethingWith( bar ); return this; }, } ); Class( 'FooDecorator', { 'private _foo': null, // ... 'public performOperation': function( bar ) { return this._foo.performOperation( bar ); }, } ); In the above example, `FooDecorator` is a decorator for `Foo`. Assume that the `getValueOf()` method is undecorated and simply needs to be proxied to its component --- an instance of `Foo`. (It is not uncommon that a decorator, proxy, or related class will alter certain functionality while leaving much of it unchanged.) In order to do so, we can use this generic, boilerplate code return this.obj.func.apply( this.obj, arguments ); which would need to be repeated again and again for *each method that needs to be proxied*. We also have another problem --- `Foo.getValueOf()` returns *itself*, which `FooDecorator` *also* returns. This breaks encapsulation, so we instead need to return ourself: 'public performOperation': function( bar ) { this._foo.performOperation( bar ); return this; }, Our boilerplate code then becomes: var ret = this.obj.func.apply( this.obj, arguments ); return ( ret === this.obj ) ? this : ret; Alternatively, we could use the `proxy' keyword: Class( 'FooDecorator2', { 'private _foo': null, // ... 'public proxy performOperation': '_foo', } ); `FooDecorator2.getValueOf()` and `FooDecorator.getValueOf()` both perform the exact same task --- proxy the entire call to another object and return its result, unless the result is the component, in which case the decorator itself is returned. Proxies, as of this commit, accomplish the following: - All arguments are forwarded to the destination - The return value is forwarded to the caller - If the destination returns a reference to itself, it will be replaced with a reference to the caller's context (`this`). - If the call is expected to fail, either because the destination is not an object or because the requested method is not a function, a useful error will be immediately thrown (rather than the potentially cryptic one that would otherwise result, requiring analysis of the stack trace). N.B. As of this commit, static proxies do not yet function properly.
2012-05-02 13:26:47 -04:00
this.proxyFactoryCall,
"Proxy factory should be called with proper arguments"
);
// ensure it was properly generated (use a strict check to ensure the
// *proper* value is returned)
this.assertStrictEqual(
this.proxyReturnValue,
this.members[ 'public' ][ name ],
"Generated proxy method should be properly assigned to members"
);
},
/**
* A weak abstract method may exist in a situation where a code
* generator is not certain whether a concrete implementation may be
* provided. In this case, we would not want to actually create an
* abstract method if a concrete one already exists.
*/
'Weak abstract methods are not processed if concrete is available':
function()
{
var _self = this,
called = false,
cid = 1,
name = 'foo',
cval = function() { called = true; },
aval = [],
ckeywords = {},
akeywords = { weak: true, 'abstract': true, },
instCallback = function() {}
;
// first define abstract
this.assertOk( this.sut.buildMethod(
this.members, {}, name, aval, akeywords, instCallback, cid, {}
) );
// concrete should take precedence
this.assertOk( this.sut.buildMethod(
this.members, {}, name, cval, ckeywords, instCallback, cid, {}
) );
this.members[ 'public' ].foo();
this.assertOk( called, "Concrete method did not take precedence" );
// now try abstract again to ensure this works from both directions
this.assertOk( this.sut.buildMethod(
this.members, {}, name, aval, akeywords, instCallback, cid, {}
) === false );
this.members[ 'public' ].foo();
this.assertOk( called, "Concrete method unkept" );
},
/**
* Same concept as the above, but with virtual methods (which have a
* concrete implementation available by default).
*/
'Weak virtual methods are not processed if override is available':
function()
{
var _self = this,
called = false,
cid = 1,
name = 'foo',
oval = function() { called = true; },
vval = function()
{
_self.fail( true, false, "Method not overridden." );
},
okeywords = { 'override': true },
vkeywords = { weak: true, 'virtual': true },
instCallback = function() {}
;
// define the virtual method
this.assertOk( this.sut.buildMethod(
this.members, {}, name, vval, vkeywords, instCallback, cid, {}
) );
// override should take precedence
this.assertOk( this.sut.buildMethod(
this.members, {}, name, oval, okeywords, instCallback, cid, {}
) );
this.members[ 'public' ].foo();
this.assertOk( called, "Override did not take precedence" );
// now try virtual again to ensure this works from both directions
this.assertOk( this.sut.buildMethod(
this.members, {}, name, vval, vkeywords, instCallback, cid, {}
) === false );
this.members[ 'public' ].foo();
this.assertOk( called, "Override unkept" );
},
Private methods are no longer wrapped This is an exciting performance optimization that seems to have eluded me for a surprisingly long time, given that the realization was quite random. ease.js accomplishes much of its work through a method wrapper---each and every method definition (well, until now) was wrapped in a closure that performed a number of steps, depending on the type of wrapper involved: 1. All wrappers perform a context lookup, binding to the instance's private member object of the class that defined that particular method. (See "Implementation Details" in the manual for more information.) 2. This context is restored upon returning from the call: if a method returns `this', it is instead converted back to the context in which the method was invoked, which prevents the private member object from leaking out of a public interface. 3. In the event of an override, this.__super is set up (and torn down). There are other details (e.g. the method wrapper used for method proxies), but for the sake of this particular commit, those are the only ones that really matter. There are a couple of important details to notice: - Private members are only ever accessible from within the context of the private member object, which is always the context when executing a method. - Private methods cannot be overridden, as they cannot be inherited. Consequently: 1. We do not need to perform a context lookup: we are already in the proper context. 2. We do not need to restore the context, as we never needed to change it to begin with. 3. this.__super is never applicable. Method wrappers are therefore never necessary for private methods; they have therefore been removed. This has some interesting performance implications. While in most cases the overhead of method wrapping is not a bottleneck, it can have a strong impact in the event of frequent method calls or heavily recursive algorithms. There was one particular problem that ease.js suffered from, which is mentioned in the manual: recursive calls to methods in ease.js were not recommended because it (a) made two function calls for each method call, effectively halving the remaining call stack size, and (b) tail call optimization could not be performed, because recursion invoked the wrapper, *not* the function that was wrapped. By removing the method wrapper on private methods, we solve both of these problems; now, heavily recursive algorithms need only use private methods (which could always be exposed through a protected or public API) when recursing to entirely avoid any performance penalty by using ease.js. Running the test cases on my system (your results may vary) before and after the patch, we have: BEFORE: 0.170s (x1000 = 0.0001700000s each): Declare 1000 anonymous classes with private members 0.021s (x500000 = 0.0000000420s each): Invoke private methods internally AFTER: 0.151s (x1000 = 0.0001510000s each): Declare 1000 anonymous classes with private members 0.004s (x500000 = 0.0000000080s each): Invoke private methods internally This is all the more motivation to use private members, which enforces encapsulation; keep in mind that, because use of private members is the ideal in well-encapsulated and well-factored code, ease.js has been designed to perform best under those circumstances.
2014-03-20 22:36:43 -04:00
/**
* This is a beautiful consequence of the necessay context in which
* private methods must be invoked.
*
* If a method has the ability to call a private method, then we must
* already be within a private context (that is---using the private
* member object, which happens whenever we're executing a method of
* that class). The purpose of the method wrapper is to (a) determine
* the proper context, (b) set up super method references, and (c)
* restore the context in the event that the method returns `this'. Not
* a single one of these applies: (a) is void beacuse we are already in
* the proper context; (b) is not applicable since private methods
* cannot have a super method; and (c) we do not need to restore context
* before returning because the context would be the same (per (a)).
*
* That has excellent performance implications: not only do we reduce
* class building times for private methods, but we also improve method
* invocation times, since we do not have to invoke a *closure* for each
* and every method call. Further, recursive private methods are no
* longer an issue since they do not gobble up the stack faster and,
* consequently, the JavaScript engine can now take advantage of tail
* call optimizations.
*
* This is also further encouragement to use private members. :)
*/
'Private methods are not wrapped': function()
{
var f = function() {},
name = 'foo';
this.sut.buildMethod(
this.members, {}, name, f, { 'private': true },
function() {}, 1, {}
);
// if the private method was not wrapped, then it should have been
// assigned to the member object unencapsulated
this.assertStrictEqual( this.members[ 'private' ][ name ], f );
},
[#25] Finished refactoring MemberBuilder/MethodTest and removed inc-member_builder-common (no longer needed) Finally feels like things are starting to come together. It's rather interesting looking back. Each time I begin writing a piece of software, I think to myself, "This is the best way to do it." Well, generally. Perhaps the implementation could have been better, but I may not have had the time. However, the general concept remains. Each time I look back months later and find that I disagree with certain decisions. I find certain implementations to be messy or poorly constructed. Or perhaps I was just being lazy to begin with. Whatever the case, it is comforting. It shows that one is continuing to learn and evolve. Now, in the case of ease.js, we're working with a number of different factors in regards to my perception of prior code quality. Primarily, I'm looking at a basic implementation (in this case, I'm referring to test cases) that served as a foundation that could be later evolved. I didn't have the time to devote to a stronger solution. However, since the project has evolved so far past my original expectations, a more sophisticated solution is needed in order to simplify the overall design. That is what happened here. Of course, we're also looking at a year's worth of additional, intimate experience with a language. Regardless of the reason, I love to see software evolve. Especially my own. It's as if I'm watching my child grow. From that, I can get a great deal of satisfaction. One shouldn't expect perfection. But one should certainly aim for it.
2011-10-26 23:38:43 -04:00
} );