Category Image Reusable Stateless Components


Stateless WOComponents result in low memory usage (generally only one instance of the a stateless component exists per application thread) and it's functionality is reused over and over and shared among all pages ( and sessions)...

Typically I implement all my reusable subcomponents as a subclass of a custom WOComponent subclass named "WKRCComponent" (you can use whatever name you wish). WKRCComponent subclasses WOComponent and implements the code necessary to make a WOComponent "stateless" and "non-synchronizing" .

To tell the WebObjects framework that a WOComponent is non-synchronizing, you simply override the default synchronizesVariablesWithBinding method to return false. This basically turns off the "magic" pulling and pushing of bindings between parent WOComponents and the sub-WOComponents that they contain. Now why would you want to do this? Well, the primary reasons for me are predictability and efficiency. The consequence of turning off automatic binding synchronization is that you should use lazy initialization to pull bindings from parent components and much more rarely use setValueForBinding( object, bindingString ) to push binding values from a subcomponent to en enclosing parent WOComponent.

/** Returns false to turn off automatic binding synchronization */
public boolean synchronizeVariablesWithBindings() {
return false;
}



To tell the WebObjects framework that a WOComponent subclass is stateless you simply override the default isStateless method to return a value of true. The implication of this is that your stateless WOComponent will be instantiated only once per application thread compared to non-stateless components that get instantiated every time they are used on a new page. This will reduce memory usage in WebObjects apps aswell as perhaps save instantiation time. In any case these are the only reasons to make components stateless.

/** Returns true to make this a stateless component */
public boolean isStateless() {
return true;
}


Now, if you make a WOComponent stateless, then you need to implement the reset() method which is called automatically by the WebObjects framework in between sharing the component across different pages (which may be generated for different users in different sessions). Failure to reset, or simply set ivars (instance variables) to null will result in those ivar values showing up in the next page that uses the stateless component which could mean unintentionally sharing information and other unintended consequences! Think of reset as necessary to initialize the WOComponent to the state it would be in if it was newly created.

Using reset()

/** Sets ivars to null */
public void reset() {
// Set ivars to null
_account = null;
}

Posted: Wednesday - July 20, 2005 at 10:41 PM        


Published by