Command Pattern (Abstracted value-objects in/out of EJB)


J2EE patterns: Command Pattern (Abstracted value-objects in/out of EJB)

  1. Preparation:
    Review and understand the 'Command pattern' in 'Patterns In Java Volume 1', Mark Grand, Wiley; or visit IBM's website and download their Patterns PDK.


    The first step is to map all the logical transactions and data elements to value-objects you will be sending back and forth between your web server and EJB tier as 'commands'.

    The goal is for the jsp/servlet layer (presentation) to interface with the EJB layer though a controller that translates requests for information or updates into concrete commands. These commands are typically 'verb named' to represent the request, and are designed to to execute within the EBJ container in partnership with a specific EJB session bean.
    i.e. When a servlet needs information on a 'Car' it asks the presentation controller to 'findCarData(String modelNumber)'. This controller services the request by instantiating a 'FindCarCommand(modelNumber)' object, connecting to the command 'router' on the EJB tier and delivering the command there.

    This EJB-side router accepts the FindCarCommand object and delivers it to the EJB session bean(s) that support it. It passes the discovered session bean into the command through its 'doIt(Object sessionBean)' method.

    The command is now executing in the EJB context as its 'doIt' method pulls the car attributes like 'color' and 'engine size' from the passed-in session bean, after re-casting it to its concrete type. When program flow returns to the presentation controller, it has a fully populated FindCarCommand that it can now return elements out of to the calling servlet.


    - This 'Command' pattern de-couples the web server presentation logic from business logic in the EJB server.

    - These commands can be re-used by other applications or presentation models (intranet applications) that call into the EJB command router.

    - The presentation side controller can attach to multiple EJB servers (routers), allowing for load balancing or failover.

    - Only one RMI/IIOP call is used to send the value-object (command) across the wire, rather than a servlet making multiple calls to read a session/entity beans attributes.

    Threaded Messages (22)

  2. Bob,

    I have done exactly the same thing on our web channel.
    We dont have EJB yet but I implmented the equivalent of
    a stateless session bean as a service. The services
    return instances of a generic wrapper class. The controller
    therefor does not need to know about the details of the wrapper.
                 / \
              user car
             details details

    Have you thought about using JSP Taglets to pass on the
    presentation logic to reusable tag components. Therefor
    the only things that need to know about wrapper details
    are the services and the JSP tags.
  3. I am a fan of the Command pattern, in fact a project I have involvement with has just implemented this framework for the web server.

    The pattern, as outlined here, does form a fairly solid link with EJB, which means it is only reusable in that space. This is not necessarily a problem but it is relatively straight forward to break this link and make the whole thing more reusable...

    * The doIt (execute) method, should not take a SessionBean as a parameter. The standard Command interface should simply have a parameterless doIt method. (This assumes that any relevant command parameters are passed in at construction stage, but nothing related to the EJB is passed in.)
    * An AbstractCommand class may exist, this is optional.
    * An AbstractEJBCommand class would exist; this would extend AbstractCommand if it existed.
    * The doIt method of the ConcreteEJBCommand (extends AbstractEJBCommand) would then discover the relevant session bean. This discovery functionality would be implemented in the abstract class via a setJNDIHome(name) and getEJB() methods and called from the doIt method of the ConcreteEJBCommand.
    * The doIt method could then execute within the context of that EJB.

    This means that you still get the tie in with EJB but aren't forced to have it.



  4. I have used the Command pattern in a different way ( not in the EJB tier ) & found it to be extremely useful when coupled with Java's Reflection. I have a setup like this...

    Applet <--> Servlets <--> Session EJB <--> Entity EJB <--> DataBase

    I have used the Command objects while forwarding POST/GET requests from the applet to the Servlet. I have a single Controller/Gateway Servlet on my app server whose only function is to forward service requests to other Servlets/EJBs.
    This Gateway servlet only knows of a Service Interface and how to invoke the services in that Interface.
    On the EJB side, I have used a Session bean facade for entity beans. This works quite well.
  5. We have also had success with the Command pattern, but as pointed out here, without directly tying into EJB.

    In this model, a CommandExecutor interface is responsible for invoking the command. A particular implementation of the CommandExecutor could then be an EJB client that can send the Command to the EJB for execution remotely.

    Commands of course must be serializable, and the CommandExecutor implmentation must call "doIt" or "execute" in the remote context. From a client perspective, to invoke a command, you basically create it, send it information (in the constructor or by properties), and use a CommandExecutor to call "Command invoke( Command c)" or similar. This method is responsible for triggering the Command's execution and returning its results as an equivalent Command (a variation of the Detail pattern).


  6. In my experience command pattern is not the best approach to an EJB. Now, I understand that it may be a complete success on your project, but for any project that gets past first release, there is a maintenance phase; and believe me when I say that maintaining system written based on this pattern is not that easy. Besides, you are actually coupling your App tier to your Business tier with usage of command pattern by the concept of the command itself.

    In my experience a better approach is to create a 'Facade' or a set of 'Facade' like classes that actually abstract behaviour of the business in question, this will definetelly make a life easier for developers and maintainers.

    Anyway, decopuling App tier from Business tier never works in practice for large scale projects.

    regards, Mikhail.
  7. Mikhail, could you perhaps elaborate on your assertions? In particular, why does decoupling the App and Business (Service) layers never work in practice for large-scale projects?


  8. I would have to agree with Mikhail. I'm not saying that the Command pattern isn't a good idea, but I can't say that I would use it. I've always stuck with this pattern and for me it has proved optimal and I don't always use the same pattern. Ofcourse, it depends on what I'm try to do. I normally don't like to put lots of code in a JSP, especially a bunch of catch statements.

    JSP --> JavaBean or Servlet --> SessionBean 1..* EntityBean

  9. I forgot to add that I use bulk accessor methods to pull value-objects that are aggregates of my entity beans. The value objects have an abstraction. For instance, an Account bean has a BillingAddress, ResidentialAddress, FraudData, CreditCard and so on. When I would process CreditCard information in my account bean....I would have an accessor method getCreditCard() or setCreditCard() therefore I wouldn't have to get or set individual attributes of credit card information like setCreditCardNumber() or setNameOnCard(). These methods I would call from a SessionBean, but that method might model business functionality like: registerUser() and that would possibly use 1 or many EntityBeans.
  10. Well I guess you good call this a design pattern,

    JSP --> JavaBean or Servlet --> SessionBean 1..* EntityBean

    but it is really a set of scripts?! When your architecture grows how are you going to cleanly separate out which script or set of EJB's perform a task. There really isn't a clean separation of what your are doing with how you do it.
  11. Tim.

    The answer is very simple. First imagine that you have 1000s of commands in your application.

    Firt, your presentation side component responsible fro creation of commands has to be super bloated and be avare of all the little intricacies of invoking a particular command. Second you EJB or other middle-tier component that searches for components that handle the command would have to have an incredible amount of knowledge of who handles the command.

    In the explanation of the pattern in the thread. There is a doIt signature that requires the knowledge of which bean handles each command. Since it has to do that casting to the appropriate type. I understand that strategy pattern could be used here that creates an interface that handler of the command will have to support. Still, your system will turn into a million-class march as soon as functionality broadens past 100 commands. Or you will have to abstract some of the commands and have allot of logic inside command handlers on what exactly they need to do.

    Instead the approach I see working better and cleaner, is to categorize the system by services it performs. Example could be CarDomainService wich would be responcible for finding cars, creating cars, updating cars, ...

    It has been my experience that this kind of Facade like behaviour is a much cleaner approach.
  12. After applying a form of the command pattern in our current rapidly exanding EJB project I tend to agree that it is not suitable when there are a large number of commands involved. We found that there was a real proliferation of command classes being created. We ended up replacing whole sets of command classes with a small number of façades or proxies of our service (session bean) interfaces. This has greatly reduced the number of classes involved -- an advantage that will become more apparent as the number and size of our service interfaces grows over the life of our project.

  13. Is the Command Pattern and the MVC (Model View Control) Pattern the same? If not, what are the main differences?
  14. Passing commands or actions to the EJB side as this pattern suggests has both conceptual and practical benefits.

    Conceptually, some of the things we want to do with beans belong with the bean itself; i.e. it's almost a violation of encapsulation for a client to access each field of a bean to accomplish certain actions. If we instead have the beans perform these actions itself, the bean deals with its own field access.

    From a practical point of view, sending actions to the beans so that they may perform them improves performance and reliability. These improvements stem from the principle of locality - elimination of remote method invocations.

    Rather than using the command pattern, however, I would use the Acyclic Visitor Pattern. With the Acyclic Visitor Pattern, you would pass the session bean a visitor. In this case the visitor would be an action or command. The session bean would turn back around and invoke the action. Giving the bean access to the action before invoking it allows the bean to do type checking and casting to make sure the action applies to that type of bean.

    See the publications section of for more information on the Acyclic Visitor Pattern.
  15. How did you used the Acyclic Visitor Pattern ? I've read the document from objectmentor and they say that the language you use must allow multiple inheretance. How did you implement this in Java? Have you used interfaces for this ? Can you give an example ?
  16. The Acyclic Visitor Pattern does, in fact, require multiple inheritance, but only multiple inheritance of interfaces.

    Here's how to do it:

    1. Write an IBeanAction interface with no methods.

    2. Add a performAction() method to your session or entity bean. Have the method take an instance of the IAction interface.

    3. Write an IXXXAction interface with a single perform(XXX xxx) method (where XXX is the name of the remote interface of your bean).

    4. Implement the performAction() method of your bean to check if the action passed in is an instance of IXXXAction. If it is, then downcast the action to IXXXAction and invoke its perform(XXX xxx) method.

    5. Write a concrete class that implements the IXXXAction and interfaces.

    6. Write client code that instantiates your concrete action class and passes it to the performAction() method of the bean.

    I have used this pattern many times in Java, and have just recently begun using it in my EJBs.
  17. Just wondering if you have implemented this on EJB in the session bean passing a command parameter of ICommand (interface) or alike?

    I am very anxious for this as I have too implemented command pattern in interface parameter way. However, I get a "marshelException" error.

  18. My previous message contained some errors. Here is a corrected version.


    The Acyclic Visitor Pattern does, in fact, require multiple inheritance, but only multiple inheritance of interfaces.

    Here's how to do it:

    1. Write an IBeanAction interface with no methods.

    2. Add a performAction() method to your session or entity bean. Have the method take an instance of the IBeanAction interface.

    3. Write an IXXXAction interface with a single perform(XXX xxx) method (where XXX is the name of the remote interface of your bean). This interface should extend the IBeanAction interface.

    4. Implement the performAction() method of your bean to check if the action passed in is an instance of IXXXAction. If it is, then downcast the action to IXXXAction and invoke its perform(XXX xxx) method.

    5. Write a concrete class that implements the IXXXAction and interfaces.

    6. Write client code that instantiates your concrete action class and passes it to the performAction() method of the bean.

    I have used this pattern many times in Java, and have just recently begun using it in my EJBs.
  19. Taking up your comment about saving on RMI-IIOP calls, surely the command object doIt() method would call just a single method on the target EJB anyway thus saving you nothing at all. If you're suggesting that doIt() should do complicated logic involving many method calls (possibly including getters), then I would say that encapsulation is broken and the doIt() body should be copied to be a method on the EJB itself and doIt() should then delegate to that method.

    With this in mind, the only benefit I can see in with using the command pattern is in order to increase the granularity of visible functionality to the client, i.e. the client need only be able to use a single command at the extreme and therefore a single corresponding EJB method. But I would say a session bean facade would be a more appropriate design solution simply because whilst not as generalised, it reduces the design complexity the command pattern brings.
  20. I have not used the command pattern in an actual project, but looking into IBMs documentation I have the following concerns:

    - Why would you like to couple data and business-logic. If you are overloading a method (command) this means you have to establish a inheritance tree for that command. This seems very unconvenient compared to overloading an EJB method.
    - If the command also need to accept data in xml-format, should the command object do the parsing?
    - By having the commands as objects at the client, in effect you have to upgrade the client to change the business logic.
    -Maintainability of all the classes to be written?

    To me it looks more convenient to keep the business logic in the EJBs, but still use a value-object for passing in parameters. Especially when using the "Business Interface" pattern.

    Any comments?


  21. I agree with Andreas. I believe the Command pattern as presented here couples the client application logic with the business layer too closely (as already mentioned in a few responses above).

    However, I still have found it useful to use the Command pattern in a more restricted role. Encapsulating application actions in Commands helps me enable a clean and usable implementation of a Controller (or dispatcher) servlet for my Web application.

    This implementation is explained in the book "Web Development with JavaServer Pages" by Fields and Kolb. We can provide a simple CommandFactory that uses the Class.forName() method to create a Command instance dynamically using the command identifier provided in the request (I'm just about quoting the book verbatim here). By making every Command implement an interface, the dispatcher servlet can then simply invoke the "execute" method on the Command instance returned.

    This provides the following benefits:
    - Provides a nice "point of delegation" for the dispatcher to initiate work to be done for the particular request. The dispatcher can focus on Application wide concerns (such as authentication)
    - No need for cluttered conditional statements in the dispatcher to determine which Command to invoke to handle a request
    - Promotes reusability and maintainability by placing application action handling logic in one place.

    As for how the command would interact with EJBs to get its work done... I am looking at providing a Business Server Layer (a mesh of the Facade and Business Interface pattern). The Command object will simply call (usually one) Service object(s) (which might be Session EJBs or might be normal classes) to do the necessary business logic work. This differs to the pattern described in this thread, which suggests sending the Command object to the Service layer (or the EJB layer) and invoking it there.

    As an aside, responding to this thread has brought to mind an interesting observation. It seems to me that while we are trying to create a Business Service layer, reusable by many applications, we often have to create "facade" methods in response to the needs of a particular application - for practical reasons (like the cost of network calls). So the whole rationale can get back to front.

    An example of this situation might be: a screen has been designed that saves data into 3 different db tables. For transactional and performance reasons, we don't want the client to update the model/entity objects directly, so we create a facade method to handle the entire transaction.

    This facade method we created isn't very reusable, because it was created to cater for this (possibly unique) situation. Could this be a "Pro" for the pattern described in this thread which implicitly argues that you should not/cannot decouple Client application logic from business logic? Any thoughts?

  22. Using the command pattern is a nice way to decouple businness and presentation logic. I use it for the second project now. But there is still one big question mark for me: How to pass complex data to and from the commands?

    I mean: Sometimes it is not enough or usefull to just pass plain and eays datatypes to and from th commands. Sometimes you just need the object structure and the associations.

    What I did so far was building plain java objects representing the entity EJBs one by one.

    But that´s a lot of work and needs a lot of mapping...

    Any hints?
  23. I am in the process of implementing a command pattern to abstract ejb access between client and server. In the command pattern I am implementing, I am using a Command object that gets passed through the Proxy/Business Delegate to the Facade, and to the correct ejb. I have written a BusinessObjectController Bean which I use as a base class for all of my ejb's in hopes that I can use 1 home and remote interface for all of them. I have 1 public method called executeCommand(Command) across all my beans. Everything else is private. They have in a sense become their own command controllers, and decipher the command internally to call private methods.
    Like I said, this is an initial concept and implementation is coming shortly. Does anyone see any major problems with using the command pattern this way? If so, could you please give me some pointers?