To EJB, or not to EJB: that is the question.
Whether 'tis nobler in the mind, to suffer
The slings and arrows of outrageous licensing;
Or to take arms against a sea of potential overheads and features,
And by opposing end them? To roll your own: to reinvent the wheel;
No more; and by reinvent, to say, we continue
The heart-ache of low-level systems maintained in-house,
and the thousand natural shocks
That flesh is heir to; 'tis a consummation
Devoutly to be avoided.
(For Shakespeare's original "To be, or not to be," speech from Hamlet, see the sidebar.)
Once you have forgiven me for taking Hamlet apart with a chainsaw, you will realize that the lines above sum up the quandary every J2EE (Java 2 Platform, Enterprise Edition) architect faces: Are you over engineering your solution by employing EJB (Enterprise JavaBean) technology when the signs point to a different approach, indeed, perhaps a different technology? On the other hand, if you decide not to specify an EJB-based solution, have you subsequently found that a sizeable chunk of your code (that must be maintained) handles tasks best addressed by a container or a server?
This article shares with you how I methodically answer these questions.
Before I begin, let me set your expectations and explain my motivations for writing this article. First up, I do not answer the EJB/not EJB question for you, but I do provide a toolkit with which you can answer that question for yourself. Second, I have no hidden agendas: I do not represent an EJB server vendor, so I won't push EJBs for everything. On the other hand, I do not represent a technology or technique competing with EJB, apart from presenting it to you here as an alternative, so I won't deride an EJB solution where it makes sense.
Indeed, my motivation for this article stems from reader requests following my last JavaWorld article, "J2EE Project Dangers." In that article, I briefly touched on the danger of over-engineering, specifically around EJBs. Many readers requested a more in-depth treatise on the subject -- so here it is!
With that in mind, I propose to proceed as follows: In order to understand if you need EJB, you must understand an EJB solution's main advantages and disadvantages. As with all technologies, EJB has its weak points, and knowing these weak points is the first step to avoiding them. Following the discussion on EJB's weaknesses, I briefly outline alternatives to an EJB-based solution, both inside and outside the Java/J2EE world.
The final section is a proofing check. When you reach this part of the article, you should be comfortable applying the principles previously outlined to any business scenario. In that section, I present a progressive scenario that requires a solution (I promise not to pick either a pet store or an ATM machine!), make my call on the EJB/no EJB decision, and let you agree or disagree with my reasoning.
EJB advantages and disadvantages
Moving along, let's look at EJB's strong and weak points. In the disadvantages section, I also give solutions to commonly encountered EJB weaknesses.
First, let's examine the advantages that the EJB architecture and programming model provides:
The underpinning EJB specification: Funnily enough, EJB's main advantage -- its specification -- also represents its biggest disadvantage, as you'll see below. The specification stipulates everything for EJB, from the various types, lifecycles, and restrictions, right through to roles and responsibilities. Many vendors' application servers conform to the specification, allowing you to select a best-of-breed solution.
EJB's universal nature offers application developers well-defined roles (I'll write the container and server, you write the business logic according to my APIs). Moreover, developers enjoy the certainty the spec delivers. Indeed, by choosing an EJB solution, developers benefit from a large skills pool, along with established best practices and open standards. Finally, found a show-stopper bug in your current server? If you have paid attention to portability issues in your design and implementation, with EJB you can circumvent it by moving to another vendor with minimum effort.
Integration with the J2EE platform: Since Sun introduced EJB in 1997, a strong enterprise computing environment has grown up around it, including technologies such as servlets, JMS (Java Message Service), JSP (JavaServer Pages), the JCA (Java Connector Architecture), JDBC (Java Database Connectivity), security, and transaction management. Such integration enhances EJB's attractiveness as the J2EE platform includes so much other complementary technology.
For you, the application architect or developer, you can rest easy because no matter how complex your application, the integrated, fully featured J2EE platform can handle your requirements.
- Almost transparent scalability: Because you delegate so much to the container, the vendor can scale server-side resources to meet fluctuations in demand. I say "almost transparent" because developers are somewhat affected. In the case of horizontal scaling and entity beans, for example, where application servers are clustered, you usually need to modify deployment descriptors to let individual server instances know they are not the only processes accessing and modifying a persistent store.
- Free access and usage of complex resources: When you buy a specification-compliant EJB server, you receive important features for free, namely transaction and security management, resource pooling, JNDI (Java Naming and Directory Interface), component lifecycle management, and more -- representing heaps of systems-level code you would otherwise have to design, build, and maintain in-house.
- A strong and vibrant industry and community: All the major IT players, with the exception of Microsoft, support EJB and J2EE, which means you are investing in a technology in which many other people have also invested. That investment commitment means the technology will be around for a long time. Additionally, enterprise Java technology continuously improves. For example, the EJB specification is currently at 2.0, having evolved from 1.0 and 1.1; a pattern likely to continue.
Surprise, surprise, despite all the marketing hype over the past three years, adopting an EJB solution does present some disadvantages. Even more surprising, despite what you may have read over the past six months about these disadvantages, they are almost all avoidable when you know how:
- Large, complicated specification: In defense of Sun, no widely adopted distributed technology has avoided this pitfall; take a look at the CORBA specifications from the OMG (Object Management Group), or the architecture of Microsoft's .Net platform. Still, it would be good if there were a trail to follow in the specification for different roles. For example, EJB developers need only read Chapters 6 and 9 of the spec to understand session and entity beans. Additionally, in my experience two roles, not the six assumed in the spec, exist in practice: container/server providers and application providers, who build, assemble, deploy, and also administrate an EJB server. As such, the specification should reflect how EJBs are used in practice and how development teams are organized.
Increased development time: I mention EJB development time in comparison to straight Java class development, not to other distributed environments. EJBs do take longer to develop, and when things go wrong, they can prove more difficult to debug, particularly because the bug might not be in your code but in the application server/container itself. Again, a difficult pitfall to avoid since the container gives you so much, but a disadvantage nonetheless.
However, timely and targeted training can solve this problem. Knowing what the container/server should provide (by understanding the specification) and knowing how the container/server provides this (vendor documentation, sometimes augmented by training) will reduce EJB development time dramatically. On a technical note, an IDE that supports the Java Platform Debugger Architecture (JPDA) also proves invaluable in tracking down bugs.
Added complexity compared to straight Java classes: At a superficial level, you require three classes for every session bean, four for an entity bean, and you may additionally employ value objects to reduce network overhead, adding another class. And I haven't counted the deployment descriptors yet, one that stores standard EJB information, the other with vendor-specific information!
The solution: auto-generation. Tools like XDoclet reduce the amount of code you have to write, and it's free! Most IDEs feature auto-generation capabilities too, but they tie you to one vendor, and usually in a GUI-driven mode too, which means no automated builds or tests -- not a great solution.
- Potential to produce a more complex and costly solution than is necessary: The potential complexity and cost is a corollary of disadvantage number one concerning the complexity of the spec. Simply put, "If you don't get it, it will get you." That is, if you don't understand EJB, you won't take full advantage of it. Moreover, you will misuse parts of it and reinvent others, making your solution less maintainable and one that fails to capitalize on the advantages that make EJB a good idea in the first place.
- Continual specification revisions: No sooner have you deployed your shiny new EJB application than you see a new specification with newer features, rendering your application obsolete before it hits the streets. This situation, however, is unavoidable. As EJB technology matures, loose ends in earlier versions are tied up and new features added. Vendor release cycles contract in sympathy, and you need to move with them. Companies today upgrade application servers much more rapidly than they did databases three or four years ago, placing additional pressure on already tightened IT budgets.
So, if you are really uneasy about going down the EJB route, what alternatives exist? Well, assuming you want to stay with Java or employ another mainstream technology, then the answer is -- not many. I've listed below the main alternatives.
Avoid EJB completely, yet still employ a Java solution
Don't use EJB; simply write straight Java classes. This solution means you must explicitly handle (or ignore) issues such as multithreading, scalability, and transaction management yourself. Now if these issues don't affect your scenario, then there is no value in using EJB (or any comparable technology), so writing straight Java makes sense.
If, however, you must address those issues, and you still decide to forgo EJB, then you must write systems-level code as solutions. Such systems code usually starts out as a couple of base classes with utility methods like
closeConnection(), plus a couple of
XXXManagers, then quickly mushrooms into your own custom version of a stripped-down container that must be maintained in-house -- not a good solution.
Adopt an EJB-friendly design
As another alternative, you can plump for a solution that makes it easy to adopt EJB at a later stage. A number of widely available design patterns make this choice feasible; in fact "Designing Enterprise Applications with the J2EE Platform" uses many such patterns. More often than not, the adopted solution is usually a Model 2 architecture, with good separation between presentation (JSPs) and business logic (servlets), in preparation for a more robust and scalable middle tier in the future.
Move to a completely different technology
If you wonder whether Java technology is right for you, then take a look at CORBA or .Net. Other options exist, but these two represent by far the main competitors to EJB/J2EE.
Don't think about going to CORBA if you think EJB/J2EE is overkill for your needs, as CORBA is at least as comprehensive. In any event, the J2EE platform has supplanted CORBA as the premier open standards-based, cross-platform enterprise computing solution. All vendors who previously sold CORBA implementations now offer J2EE implementations.
Meanwhile, Microsoft has been pushing .Net heavily. .Net is language independent and platform dependent (EJB is language dependent and platform independent). By and large, the design and feature-sets of .Net and J2EE map very closely. At present, in my opinion .Net provides no competition to J2EE. It simply hasn't been around long enough, and the architecture's key features -- particularly the common language runtime (CLR) and C# -- are new and untested in production-class systems. However, make no mistake, .Net will be a strong competitor; Microsoft led the way with DCOM (Distributed Component Object Model) and ASP (Active Server Page) and will continue to add good ideas and technology to the enterprise computing space.
Think out of the box!
If none of the preceding options float your boat, then you may consider other candidate technologies such as Jini/JavaSpaces or Sandstorm, which are not widely used: