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 {

[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.




Tuesday, December 24, 2013

Static Class in Java

Consider a class with utility methods. In this case instantiating an instance every time we need those methods, does not make sense. So what exactly should be done.

Should we go with abstract class? An abstract class may not make sense as we do not expect derived classes to provide any implementation. We can go with a static class (Here I mean a class with static methods).

So, When do we need to write a static class?
When we have a bunch of utility methods and instantiation of the class seems nonsensical.

So what is the best way to write a static class?1
Enforce noninstantiability  by using private constructor (from Effective Java, Item 4)
  1. Attempting to enforce noninstantiability by making a class abstract does not work.
  2. A default constructor is generated only if a class contains no explicit constructors, so a class can be made noninstantiable by including a private constructor:
So we need: A class with private constructor and static methods.

As the constructor is private it is not accessible to outside world so there can not be any derived class. Though not needed, we can also make the class final as there is no harm in being explicit.
// Noninstantiable utility class
public class UtilityClass
{
    // Suppress default constructor for noninstantiability
    private UtilityClass() {
        throw new AssertionError();
    }
}

An Assertion Error is a good idea as it ensures us in case the constructor is invoked accidentally with in the class. As a side effect this class cannot be extended now.

We should keep in mind one thing: Static methods are death to testability. Also they do not participate in Object Oriented world and therefore are considered bad by few people.

In the above article I used the term Static class to mean the class with static methods. Otherwise only nested classes can be static.
class OuterClass{
    public static class StaticNestedClass{
    }

    public class InnerClass{
    }

    public InnerClass getAnInnerClass(){
        return new InnerClass();
    }

    //This method doesn't work
    public static InnerClass getAnInnerClassStatically(){
        return new InnerClass();
    }
}

class OtherClass{
    //Use of a static nested class:
    private OuterClass.StaticNestedClass staticNestedClass = new OuterClass.StaticNestedClass();

    //Doesn't work
    private OuterClass.InnerClass innerClass = new OuterClass.InnerClass();

    //Use of an inner class:
    private OuterClass outerclass= new OuterClass();
    private OuterClass.InnerClass innerClass2 = outerclass.getAnInnerClass();
    private OuterClass.InnerClass innerClass3 = outerclass.new InnerClass();
}
All static methods (in fact all the methods) and static variables are stored in the PermGem section of the heap, since they are part of the reflection data (class related method and not instance related). The variables (or variable definitions) are store in PermGen section but the objects they refer to get stored somewhere on the heap. More can be found here.

More about garbage collection and memory allocation can be read here and here.

Monday, December 16, 2013

Algorithms:Intersection point of two linked lists in Y shape

Algorithms Series

We are given two linked lists that intersect at a point and then become one. The number of nodes in each list before they intersect are unknown and they may be different (m and n say). We need an algorithm to find the intersection point. This can be shown by this image:
Linked Lists

The simplest is to go with brute force where each node of the first is compared with every other node of the other list. The matching node pointers will lead us to the intersecting node. 
Lame Approach

Time complexity: O (mn)             Space Complexity: O (1)




Can we use Hash Table? Yes. 
 The approach is:
  1. Select the list having less number of nodes and store it in hash table.
  2. Traverse the second list and check whether the same node pointer exists in the hash table.
  3. If it does we get intersection point.


Intersection using marker
Time complexity: Time for creating the hash table + time for scanning the second list
O (m) + O (n)

 Space Complexity: O (n) or O (m)

Can we use stacks to solve it? Yes. The approach is as:
  1. Push both the lists on stacks. The top of both will have the last element of the lists.
  2.  Compare the top elements on two stacks.
    1. If they are same pop them and store them.
    2. If they are not, it means the common element has just popped out in previous step.
  3. The value popped out in previous step can then be returned.
Time complexity:  O (m + n)                       Space complexity: O (m + n)

Can we use the first repeating number? Yes.
  1.  Create an array and keep all the next pointers of both the lists in the array.
  2.  In the array find the first repeating element in the array. The first repeating number is the intersection point.

Time complexity:  O (m + n)                       Space complexity: O (m + n)

Do we have any other approach? Yes by combining sorting and searching.
  1.  Create an array and keep all the next pointers of first list in the array.
  2.  Sort it (assume binary sort is used O (logn) ).
  3. Then for each element in second list, search it in this sorted array.
    1. If we find it then it is intersection point.

Time complexity:  Time for sorting + Time for searching = O (Max (mlogm, nlogn))                          
Space complexity: O (Max (m, n))

Do we have any efficient approach? Yes.
The approach is to compute lengths of the two lists in linear time. Then advance the longer list by difference in length of two lists and then start comparing.
  1.  Find lengths (L1 and L2) of both the lists. O(n) + O(m) = O( Max (m, n))
  2.  Take the difference (d) of the lengths. O(1)
  3.  Make d steps in longer list. O(d)
  4. Step in both lists in parallel until links to next node match. O (Min (m, n)).

Time complexity:  O (Max (m, n))            Space Complexity: O (1)

ListNode FindIntersectingNode(ListNode list1, ListNode list2)
{
  int L1=0, L2=0, diff=0;
  ListNode head1 = list1, head2 = list2;
  while(head1 != null) {
   L1++;
   head1 = head1.getNext();
  }
  while(head2 != null) {
   L2++;
   head2 = head2.getNext();
  }
  diff = L1 – L2;
  if( L1 < L2) {
    head1 = list2;
    head2 = list1;
    diff = L2 – L1;
  }
  for(int count = 0; count < diff; count++) head1 = head1.getNext();
  while(head1 != null && head2 !+ null) {
    if(head1 == head2) return head1.getData();
    head1 = head1.getNext();
    head2 = head2.getNext();
  }
  return null;
}

Disclaimer: The images and various examples are taken from internet. I do not claim them as my own ideas. I have tried to mark the proper references but in case anything is missing please let me know.

Saturday, December 14, 2013

Algorithms:Partition of a Number

Algorithms Series

So if you do not know what do I mean by partition of a number, then here it is:

A partition of a positive integer n is, a way of writing n as a sum of positive integers. Two sums that differ only in the order of their summands are considered to be the same partition (For example 1+2+3 and 1+3+2 are same). If order matters then the sum becomes a composition.

Partition(4) = 5
 
4
3 + 1
2 + 2
2 + 1 + 1
1 + 1 + 1 + 1

Then we have another related term Restricted Partition which is partition having some constraints. For example partition having only odd numbers, partition having only 1 and 2 etc.

In number theory, the partition function p(n) represents the number of possible partitions of a natural number n, which is the number of distinct ways of representing n as a sum of natural numbers.
\sum_{n=0}^\infty p(n)x^n = \prod_{k=1}^\infty \left(\frac {1}{1-x^k} \right).

The right side term on expansion becomes:
(1 + x + x2 + x3 + ...)(1 + x2 + x4 + x6 + ...)(1 + x3 + x6 + x9 + ...) ....




Partitions can also be visualized by Young diagrams or Ferrous diagrams. 

Young Diagram makes use of boxes and Ferrous Diagrams make use of dots to represent the same information  (as shown below).


The partition 6 + 4 + 3 + 1 of the positive number 14 can be represented by:
****
***
***
**
*
*

So the problem is to write an algorithm that will print all the partitions for a number. There is one very good implementation at Princeton university page under the topic of recursion. Here it is reproduced:

public class Partition { 

    public static void partition(int n) {
        partition(n, n, "");
    }
    public static void partition(int n, int max, String prefix) {
        if (n == 0) {
            StdOut.println(prefix);
            return;
        }
  
        for (int i = Math.min(max, n); i >= 1; i--) {
            partition(n-i, i, prefix + " " + i);
        }
    }


    public static void main(String[] args) { 
        int N = Integer.parseInt(args[0]);
        partition(N);
    }

}

% java Partition 4      % java Partition 6
4                       6
3 1                     5 1
2 2                     4 2
2 1 1                   4 1 1
1 1 1 1                 3 3
                        3 2 1
                        3 1 1 1
                        2 2 2
                        2 2 1 1
                        2 1 1 1 1
                        1 1 1 1 1 1

Let me know your feedback. Thanks.

Sunday, February 24, 2013

Flash Builder shortcuts and tricks

Recently I found come really interesting and useful shortcuts in Flash Builder. I always hate unnecessary imports in the code. We have a shortcut:

ctrl + shift + o (the letter is o as in orange)

This will remove all unnecessary imports. Also to indent, select the code (as or mxml) and then use shortcut:

ctrl + i to indent a piece of code.

We can also use:

ctrl + d (to delete the current line).
ctrl + space (twice) to get all code templates.

One really good article can be found here:
http://www.adobe.com/devnet/flash-builder/articles/tips-tricks.html

Problem with ObjectUtil copy

We all have used this wonderful method copy() in ObjectUtil class. It does a deep copy of the object using the following lines of code:
public static function copy(value:Object):Object
    {
        var buffer:ByteArray = new ByteArray();
        buffer.writeObject(value);
        buffer.position = 0;
        var result:Object = buffer.readObject();
        return result;
    }

As the code implies it does not copy each and every property recursively but the object is serialized into a array of bytes which is then de-serialized to get a new object. It makes use of built in Flash player AMF capabilities and it is exactly the same serialization mechanism that is used for remoting. When we send an object using remoting we send an AMF array of bytes which is de-serialized at the other end. As AMF is used to copy few things happen:

1. If we try to cast the result of copy to a class it may fail. For example when I tried to use 'as' operator to cast the result it failed.
2. Also when we use transient metadata tag output gets affected.

When the object gets de-serialized it does not create an instance of the class automatically. The object may have all the properties but still not a true instance (rather an object of class Object or ObjectProxy) unless the AMF packet includes type information about the object. This information gets added to the packet in two ways:

1. If the remoting tag is used: [RemoteClass]
2. If the class is registered using registerClassAlias() method

If we use remoting tag then it is easy. For example:

//assume employee has [RemoteClass] metadata.
var employee:Employee = Employee (ObjectUtil.copy(emp));

We may not always have this tag. In one of my project I was having a class ProfileMetaData which was making use of various properties of other value objects and was not sent back to business layer. So there was no question of remoting. And as expected after copy() I was not able to cast the result. So we need to register the class against a string alias. For example:

registerClassAlias("com.app.vo.ProfileMetaData",ProfileMetaData);
//Now we can copy and caste
var profileCopy:ProfileMetaData = ProfileMetaData (ObjectUtil.copy (report) );

What about the transient? If a property is transient it gets removed from the AMF packet during serialization. The reason they are not sent over the network via Flash Remoting is because  they are not included in the AMF packet. So there is no question of reading them back. In some cases it is useful.

More:
http://archive.darronschall.com/weblog/2007/08/on-transient-objectutilcopy-and-casting.html
http://stackoverflow.com/questions/14576627/how-to-work-registerclassalias-method-for-custom-mxml-components