Sunday, January 26, 2014

Parsley Interview Questions

Question: Why do we need to use Parsley? What are the major features of Parsley?
Answer: Parsley is a framework based on concept of IoC (Inversion of Control) and DI (Dependency Injection), somewhat similar to Spring in Java. The major features it provides are:
  • Flexible IOC Container: Supports configuration with AS3 Metadata, MXML, XML files, ActionScript
  • Dependency Injection: Injection by type or id - for constructors, methods or properties
  • Decoupled Bindings: Bindings where source and target are fully decoupled, based on a publish/subscribe mechanism
  • Messaging Framework: Fully decoupled senders and receivers, mapping by type and not string identifiers
  • Managed Commands: Execute commands or sequences of commands or map them to messages, automatically added to the container only for the time they execute
  • Dynamic View Wiring: Easily wire Flex components to objects declared in the container
  • Advanced Modularity: Apply separate configuration and communication spaces for each tab, window, popup or Flex Module
  • Object Lifecycle: Asynchronously initializing objects, object lifecycle observers
  • Localization: Integrates with Flex ResourceManager for Flex Applications, contains its own Localization Framework for Flash Applications
  • Extensibility: Easily create your own configuration tags, a single implementation can be used as AS3 Metadata, MXML or XML tag
  • And much more...
Question: Flex also supports injection then how is it different for Parsley? 
Answer: Flex itself is a framework and it allows developers to set a data provider for a list. It is actually injection but what parsley provides is dependency injection which is automatic.

Question: Flex supports events. How are they different from messaging in Parsley? What should be preferred?
Answer: Both Flex events and Parsley messages are based on the idea of decoupling. But there are some differences:
1. Flex events traverse through the display list and we may not need it all the time.
2. Flex events depend on String for their name and that can be a problem sometimes.
3. Flex events follow their own cycle and can be cancelled during that.
Now based on the requirement we can select one of the two. Parsley can also manage the standrad flex events and they are called Managed Events.

Question: What are the various ways of dependency injection? 
Answer: There are various ways.
Constructor Injection: This is believed to be the cleanest in terms of encapsulation because it allows us to create immutable classes. We use the [InjectConstructor] tag.
Constructor Injection selects the dependency based on type, so we need to make sure that there are not more than one object of same type in the context.
package com.bookstore.actions {

class LoginAction {

    private var service:LoginService;
    private var manager:UserManager;

    function LoginAction (service:LoginService, manager:UserManager = null) {
        this.service = service;
        this.manager = manager;    

There is a nasty bug in some Flash Player versions where reflection using descibeType does not work. If we get it the workaround is to create instances of these classes before we initialize Parsley.We can simply throw away these instance, merely creating them fixes the problem.
new LoginAction();
new ShoppingCartAction();

Method Injection: This is similar, we can place [Inject]tags on  any number of methods.
package com.bookstore.actions {

class LoginAction {

    private var service:LoginService;
    private var manager:UserManager;

    public function init (service:LoginService, manager:UserManager = null) : void {
        this.service = service;
        this.manager = manager;    

Property Injection By Type: Similar to method injection but it is done for properties.
package com.bookstore.actions {

class LoginAction {

    private var manager:UserManager;
    public var service:LoginService;
    public function set manager (manager:UserManager) : void {
        this.manager = manager;

Property Injection By Id:  Here we make use of id.
public var service:LoginService;
But a better approach is to have only one instance of any type and use injection by type (angular brackets are removed due to some formatting bug).
        services:LoginServiceImpl id="defaultLoginService"
Question: What are the differences between dependency injection and decoupled bindings?
Answer: Dependency Injection provides the following advantages over Decoupled Bindings.
  1. DI is designed for robustness. If an object X is dependent on object Y (collaborator) then the container (parsley) injects a matching instance Y when the object X gets initialized. Also it will make sure that the injected object X has a life cycle at least as long as that of object Y. This guarantees that X will not suddenly go away and that is the reason why
    1. we cannot inject from a child context into a parent,
    2. we cannot inject dynamic objects unless they are defined with  tag in the Context. 
  2. In DI container gives the guarantee that all injections have already been performed when the method marked [Init] gets invoked. This simplifies internal initialization code.
  3. Any errors caused due to mis-configurations (ambiguities etc.) are already detected at Context initialization time.

Decoupled Bindings (using Parsley's [Publish] and [Subscribe]tags) offer the following advantages over Dependency Injection:

  1. This is much more dynamic than DI and it is perfectly legal for any subscriber to have no value at all or to receive multiple updates of the same property during its life cycle. It is really more the decoupled equivalent of the typical usage of Flex Bindings.
  2. The published object does not even have to be a container managed object. So this feature can be used in a more lightweight way. Publishing an object also does not cause reflection on the object (unless you specify that it should be managed), so it has benefits for performance.

Of course there is also a price to pay compared to injection:

  1. There is no guarantee that the subscribers have any values when the method marked with [Init] gets invoked on the object as the value can be published and updated at any point in time.
  2. Errors caused by misconfiguration (in particular ambuigities) are sometimes not detected at Context initialization time. They can happen anytime a new publisher enters the Context (dynamic objects can act as publishers, too).

Question: What are the various setup options to receive message in parsley?
Answer: There are various options.
MessageHandlers: This is the most common approach. We declare methods to be invoked when a particular message gets dispatched.
public function handleLogin (message:LoginMessage) : void {
MessageBinding: It is a shortcut when we want to bind a property of a class to a property to a message, that should be updated whenever a message of a matching type is dispatched.
public var user:User;
Intercepting Messages: This is optional for the receiving side. They are useful when we want to decide whether or not the messages should be passed to the remaining handlers based on application state or user decisions.
  • All registered interceptors execute before any handlers or bindings are executed (unless we set the order attribute explicitly).
  • Interceptors can optionally suspend the message processing and resume it at a later time.
 Since version 2.4 any message receiver function can also be used as an interceptor. For MessageHandler only difference is the inclusion of MessageProcessor parameter.
public function intercept (msg:LoginMessage, processor:MessageProcessor) : void {
There are two other ways as well discussed later on:
Mapping Commands to Messages and Using the Messaging API
Question: What are the various setup options to dispatch message in parsley?
Answer: There are mainly three options.
Managed Events: If the class that wants to dispatch messages is a EventDispatcher then this is the most convenient option.It requires two steps:
    1. Declare the events with regular [Event] tags.
    2. Tell parsley that these are managed events.
  1. [Event(name="loginSuccess",type="")]
    public class LoginServiceImpl extends EventDispatcher implements LoginService {
        private function handleLoginResult (user:User) : void {
            dispatchEvent(new LoginEvent("loginSuccess", user));
Since loginSuccess was declared as a managed event it will be passed to all MessageHandlers configured in Parsley.

Injected MessageDispatchers: In case we want simple message objects that nee not to participate in event cycle and all, we can create a simple class and dispatch the message using dispatcher. The below class represents a simle message:
class LoginMessage {

    public var user:User;
    public var role:String;
    function LoginMessage (user:User, role:String) {
        this.user = user;
        this.role = role;
Then we can dispatch it as below:
public class LoginServiceImpl implements LoginService {

    public var dispatcher:Function;

    private function handleLoginResult (user:User) : void {
        dispatcher(new LoginMessage(user));
Using the Messaging API: We should avoid using Parsley API to keep our classes decoupled. The MessageReceiverRegistry interface contains the following methods for registration:
function addTarget (target:MessageTarget) : void;

function addErrorHandler (handler:MessageErrorHandler) : void;

function addCommandObserver (observer:CommandObserver) : void;

There are three categories of message receivers:
  1. A MessageTarget is a regular receiver, implementing classes include MessageHandler and MessageBinding.
  2. A MessageErrorHandler corresponds to the [MessageError] tag.
  3. A CommandObserver listens to the result or error outcome of a command.
To get hold of a MessageRegistryInstance we can inject a Context instance into our class. We then pick the scope we want to apply to our receivers.
class SomeExoticClass {

    public var context:Context;
    public function init () : void {
        var registry:MessageReceiverRegistry 
                = context.scopeManager.getScope(ScopeName.GLOBAL).messageReceivers;
        var target:MessageTarget 
                = new MessageHandler(Provider.forInstance(this), "onLogin");
Finally we can also use the ScopeManager class to dispatch messages: 
context.scopeManager.dispatchMessage(new LoginMessage(user, "admin"));
When dispatching through the ScopeManager directly the message will be dispatched through all scopes managed by this Context. This way receiving side can decide the scope to listen to. In rare cases we might want to limit the choice right on the sending side. In this case we dispatch through an individual scope:
 var scope:Scope = context.scopeManager.getScope(ScopeName.LOCAL);
scope.dispatchMessage(new LoginMessage(user, "admin"));
Question: How do we write an error handler using Parsley?
Answer: We can configure a method to be invoked whenever a handler for a matching message threw an error:
public function handleError (error:IOError, message:LoginMessage) : void;
We can also create a global handler for every time of message:
public function handleError (error:Error) : void; 
As with all message handlers it can also work as an interceptor:
public function handleError (error:Error, processor:MessageProcessor) : void; 
Finally, since an error handler configured with the tag above listens to a single scope, we may want to add an error handler to every scope created by application. We can do that programmatically through the BootstrapDefaults:

var handler:DefaultMessageErrorHandler = new DefaultMessageErrorHandler();
var method:Method = ClassInfo.forInstance(this).getMethod("handleError");
handler.init(Provider.forInstance(this), method);


Question: What is message selector and how do we use it?
In the examples of MessageHandlers, MessageBindings and MessageInterceptors, the matching methods or properties were determined solely by the type (class) of the message. Sometimes it is not enough and we need to provide more refinement with custom selectors. If we are using events the type property can server as a selector:
public function handleLogin (message:LoginEvent) : void {

public function handleError (message:LoginEvent) : void {
Sometimes we declare static const for defining types and we use them directly as selector (which accepts only string) and it does not take the value of those and signal error. We should be cautious about those mistakes.
For our custom messages we can make use of selector tag.
class LoginMessage {

    public var user:User;
    public var role:String;
Now here is an example:
public function handleAdminLogin (message:LoginMessage) : void {

Question: What do we mean by global or local scope of message?
Answer: The scope allows us to dispatch messages inside a particular area of the application.
Global and Local Scopes
A global scope is created for each context that does not have a parent (usually the one (and only one) root context created at application start up) and then it is shared with all children of that context (including grandchildren of course).
Each context will create its own local scope which will not be shared with its children.

The global scope will always be default for all configuration tags where no scope is explicitly specified. The handler below listens to ProductEvents dispatched from any Context in the hierarchy as it listens to the global scope.
public function save (event:ProductEvent) : void {
The handler now listens to ProductEvents dispatched from the same Context.
[MessageHandler(selector="save", scope="local")]
public function save (event:ProductEvent) : void {
Of course all receiver type tags accept a scope attribute including: MessageBinding and MessageErrorHandler.

Question: What is the recommended scope in multi-context applications?
Answer: The global scope is the recommended default for a single-context application and for the root context in a multi-context application.For child Contexts (those created specifically for a particular area of the application like a popup, tab or module) it is recommended to switch to local as a default, so that objects in these children use a local, private communication space per default.

This is how you can switch the scope for an entire context:
parsley:ContextBuilder config="..."
    parsley:MessageSettings defaultReceiverScope="local"

Question: What is the default scope for dispatchers?
Answer: For any [MessageDispatcher] or [ManagedEvents] tag where no scope is explicitly defined the message will be dispatched through all the scopes available for that particular context. This way the receiving side can decide which scope it wants to listen to, allowing global and local receivers for the same message instance.
For cases where we want to restrict the sending side to a single scope there will be a scope attribute for the [ManagedEvents] tag:
[ManagedEvents("save,delete", scope="local")]

Question: How can we create a custom scope?
Answer: For a large AIR window we may need custom scope. The root component may create a Context with the root application as parent but then also a few child Contexts for parts within that window. If we then want to setup a messaging scope for that window only, we need a scope that spans multiple Contexts but still is not global.

The window scope is a custom scope that exists side-by-side with the two default scopes. Now how do we make parsley to do this? In our case we have two root contexts for the two window scopes. In MXML we can specify two scopes:

Or progrmmatically add the scope with the ContextBuilder DSL:
var viewRoot:DisplayObject = ...;

The name of the scope does not need to be unique as long as we make sure that two scopes with same name never overlap. This is convenient as it allows us to define a message handler for the window scope without having to think which window instance it belongs to:
[MessageHandler(selector="save", scope="window")]
public function save (event:ProductEvent) : void {
The second boolean parameter specifies whether the scope should be shared with child Contexts. So we can also create custom local scopes although it is an unusual case.


Disclaimer: Images are taken from Parsley page.

No comments: