Sunday, January 26, 2014

Parsley Interview Questions (Part 2)

Question: How do we implement synchronous and Asynchronous commands in Parsley? 
Answer:  A synchronous command may or may not return a result in execute method.
public class SimpleCommand {

    public function execute (): String {
    
        return "This is the result";
        
    }
    
}
A command is seen as asynchronous as soon as it has a public var of type Function named callback OR a method parameter of type Function in the execute method.
public class GetUserListCommand {

    [Inject("myService")]
    public var service: RemoteObject;

    public var callback: Function;

    public function execute (): void {
    
        service.getUserList().addResponder(new Responder(result, error));
        
    }
    
    private function result (result: ResultEvent): void {
        callback(result.result);
    }
    
    private function error (event: FaultEvent): void {
        callback(event.fault);
    }
    
}

When all we do is to invoke a method on RemoteObject and pass the result or fault back to parsley then there is a shortcut. This is an Asynchronous Command with AsyncToken.
public class GetUserListCommand {

    [Inject("myService")]
    public var service: RemoteObject;

    public function execute (): AsyncToken {
        return service.getUserList();
    }
    
}
If we use the above shortcut we may still want to process the result inside the command before it ispassed to other parts. The method name for result handler must be result and for error handler it must be error. It must accept one parameter of type we expect from the remote call.
public class GetUserListCommand {

    [Inject("myService")]
    public var service: RemoteObject;

    public function execute (): AsyncToken {
    
        return service.getUserList();
        
    }
    
    public function result (users: Array): void {
        
        // process users
    
    }
    
}
We can also modify the result before it gets passed to the other parts of the application.
public class GetUserProfileCommand {


    [Inject("myService")]
    public var service: RemoteObject;

    public function execute (msg: GetUserProfileMessage): AsyncToken {
    
        return service.getUserProfile(msg.userId);
        
    }
    
    public function result (profile: XML): UserProfile {
        
        return parse(profile);
    
    }
    
}




Question: How do we map command to message?
Answer:  We use MapCommand tag and may not provide the message type.
parsley:MapCommand type="{LoadUserCommand}"
In that case it will determine it from the message parameter of execute() method in the command.
public class GetUserProfileCommand {

    [Inject("myService")]
    public var service: RemoteObject;

    public function execute (msg: GetUserProfileMessage): AsyncToken {
    
        return service.getUserProfile(msg.userId);
        
    }
    
}
The commonly used way is to provide the message type as well.
parsley: MapCommand type="{LoadUserCommand}" messageType="{LoadUserMessage}"
If we want we can also provide the property values, constructor arguments etc.
parsley:MapCommand
    parsley:Command type="{LoadUserProfileCommand}"
        parsley:Property name="type" value="{UserProfile.EXTENDED}"
        parsley:Property name="cache" value="true"
    parsley:Command
parsley:MapCommand
This tag also supports various other parameters like selector, scope etc.

Question: What is a command group?
Answer:  It is a set of command that are executed as a group. This can be specified in MXML or XML.
parsley:MapCommand messageType="{LoginMessage}"
    parsley:CommandSequence
        parsley:Command type="{LoginCommand}"
        parsley:Command type="{LoadUserProfileCommand}"
    parsley:CommandSequence
parsley:MapCommand
The commands can also be executed in parallel.
parsley:MapCommand messageType="{LoadDashboardMessage}"
    parsley:ParallelCommands
        parsley:Command type="{LoadUserProfileCommand}"
        parsley:Command type="{LoadPrivateMailboxCommand}"
    parsley:ParallelCommands
parsley:MapCommand
We can also pass the results of one command to another in a sequence in a decoupled way. If LoginCommand produces an instance of User, the next command can accept it as a parameter in execute method along with other parameters.
public class GetUserProfileCommand {

    public function execute (user: User, callback: Function): void {
    
     [...]
        
    }
    
}

Question: What is a command flow?
Answer:  It adds the concept of decision points to define a dynamic sequence of commands where the next command to execute is determined by a link that inspects the result of preceding command. It can be specified in MXML and XML.
Linking by Result Type
parsley:Command type="{LoginCommand}"
    parsley:LinkResultType type="{AdminUser}" to="{loadAdminConsole}"
    parsley:LinkResultType type="{User}" to="{loadProfile}"
parsley:Command
Linking by Result Value
parsley:Command type="{LoginCommand}"
    parsley:LinkResultValue value="{Login.ADMIN}" to="{loadAdminConsole}"
    parsley:LinkResultValue value="{Login.USER}" to="{loadProfile}"
parsley:Command 
Linking by Property Value
parsley:Command type="{LoginCommand}"
    parsley:LinkResultProperty name="isAdmin" value="{true}" to="{loadAdminConsole}"
    parsley:LinkResultProperty name="isAdmin" value="{false}" to="{loadProfile}"
parsley:Command 
Linking all Results of a Command
parsley:Command type="{LoginCommand}"
    parsley:LinkAllResults to="{loadAdminConsole}"
parsley:Command 
Custom Links
A custom link class encapsulating more complex logic can be added, too. Anything that implements the LinkTaginterface can be inserted as a child tag inside the  tag:
Command type="{LoginCommand}"
    links:MyCustomLinkType
Command

Question: Can we have decoupled result handlers and command observers?
Answer:  Yes we can have and they are specified by various tags.
CommandResult: In this case the returned object of the remote call along with the original message is passed. The message type along with selector is used to determine the handler to invoke.
[CommandResult]
public function handleResult (user:User, message:LoginMessage) : void {
In case we need to process the result as early as possible we can use immediate attribute:
[CommandResult(immediate="true")]
public function handleResult (user:User, message:LoginMessage) : void {
CommandComplete: When we are not interseted in the result but want to execute some logic triggered by the completion of command we use it.
[CommandComplete]
public function userSaved (message:SaveUserMessage) : void {
CommandError: This is to used to receive the fault or error.
[CommandError]
public function handleResult (fault:FaultEvent, trigger:SaveUserMessage) : void {
Parsley also allows local result handler for the command that was executed in global scope.
[CommandResult(scope="local")]
public function handleResult (result:Object, msg:LoginMessage) : void {
    [...]
}

To be continued....

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 {

[InjectConstructor]
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;

    [Inject]
    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;
    
    [Inject]
    public var service:LoginService;
    
    [Inject(required="false")]
    public function set manager (manager:UserManager) : void {
        this.manager = manager;
    }

}
}
Property Injection By Id:  Here we make use of id.
[Inject(id="defaultLoginService")]
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).
Objects
    xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns="http://www.spicefactory.org/parsley"
    xmlns:actions="com.bookstore.services.*"
    
    fx:Declarations
    
        services:LoginServiceImpl id="defaultLoginService"
        
    fx:Declarations
        
Objects 
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.
[MessageHandler]
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.
[MessageBinding(messageProperty="user",type="com.bookstore.events.LoginMessage")]
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.
[MessageHandler]
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="com.bookstore.events.LoginEvent")]
    [Event(name="loginFailed",type="com.bookstore.events.LoginEvent")]
    [Event(name="stateChange",type="flash.events.Event")]
    [ManagedEvents("loginSuccess,loginFailure")]
    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 {

    [MessageDispatcher]
    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 {

    [Inject]
    public var context:Context;
    
    [Init]
    public function init () : void {
        var registry:MessageReceiverRegistry 
                = context.scopeManager.getScope(ScopeName.GLOBAL).messageReceivers;
        var target:MessageTarget 
                = new MessageHandler(Provider.forInstance(this), "onLogin");
        registry.addMessageTarget(target);    
    }
}
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:
[MessageError]
public function handleError (error:IOError, message:LoginMessage) : void;
We can also create a global handler for every time of message:
[MessageError]
public function handleError (error:Error) : void; 
As with all message handlers it can also work as an interceptor:
[MessageError]
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);

BootstrapDefaults.config.messageSettings.addErrorHandler(handler);

Question: What is message selector and how do we use it?
Answer:
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:
[MessageHandler(selector="loginSuccess")]
public function handleLogin (message:LoginEvent) : void {
    [...]
}

[MessageHandler(selector="loginFailure")]
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;
    
    [Selector]
    public var role:String;
    
    [...]
}
Now here is an example:
[MessageHandler(selector="admin")]
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.
[MessageHandler(selector="save")]
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"
parsley:ContextBuilder>

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 = ...;

ContextBuilder.newSetup()
    .viewRoot(viewRoot)
    .scope("window")
    .newBuilder()
        .config(FlexConfig.forClass(ServiceConfig))
        .config(FlexConfig.forClass(ControllerConfig))
        .config(XmlConfig.forFile("logging.xml"))
        .build();
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.

Part2

Disclaimer: Images are taken from Parsley page.

Saturday, January 11, 2014

Why can a constructor not be marked static in Java?

Constructors are called automatically at the time of creation of the instance of the class. A constructor is meant to set instance variables and it could not access them if it were static. So this question itself does not make sense. But, lets continue this for sake of curiosity.

Consider the following points from Java Language Specification:

  1. Constructors, static initializers, and instance initializers are not members and therefore are not inherited.
  2. If a class declares a static method m, then the declaration m is said to hide any method m', where the signature of m is a subsignature of the signature of m', in the superclasses and superinterfaces of the class that would otherwise be accessible to code in the class. 
But we have static initialization blocks which can be viewed as "static constructor":
class Foo {
  static String Bar;
  static {
     // "static constructor"
     Bar = "Hello world!";
  }
}
Actually the only method in main class that must be static is main() method, because it is invoked without creating first instance of the main class. The following are worth reading:
  1. Classes and Objects
  2. Understanding Instance and Class Members
One point to notice is: static methods are sometimes more handy than a constructor. When we have an object of immutable type (for example String) then using a constructor will always create a new object, whereas by using static methods we can reuse the same object (rather it it recommended). We can also reuse mutable objects when we know they will not be altered in anyway.