5.1 Golden HammersIn my first and second Java books, I addressed antipatterns, patterns of solutions that break in systemic ways. By far the most common antipattern is the golden hammer. As a weekend builder, I know the metaphor well. Most carpenters have a tool in the box that''s so beautiful that they want to use it for every task. I''m the poster boy. I''ve literally used a circular saw with a carbide blade to cut wire. Java developers are no different. All of us have developed favorites. In this section, I''ll lay out a beautiful set of golden hammers for your inspection. Chances are good that you''ve used one to hammer the occasional screw.
5.1.1 The AllureAn antipattern is a bitter idea that seems sweet at the time. A golden hammer attracts a Java programmer like a box of Krispy Kremes and a bottle of Jolt. The power of bad frameworks over otherwise intelligent developers has sometimes bewildered me, but I guess it''s good for business. Sometimes, programmers do the damage to themselves. Past success can cloud your judgment. I learned XML while working on a very successful project and afterwards, I wanted to use it everywhere, from writing simple, four-line configuration files to building an alternative programming language. Others have had the same experiences with CORBA, persistence frameworks, web services, and even Java itself.
184.108.40.206 The sales processOther times, aggressive marketing or sales can do you in. Understand that the stakes are high, and this industry spends millions of dollars at the drop of a hat to get you to like and use something. If you''re making a major buying decision with the help of a sales staff, be very careful. If you don''t know how the process works, you can''t make the most informed decision. Since I''ve worked in sales, I can tell you how that process works from the inside. Figure 5-1 shows a combined version of all of the technical sales processes that I have seen from the inside.
Figure 5-1. Knowing the typical J2EE sales process helps you buy smarter
5.1.2 Some ExamplesProject teams across the nation have shown me many examples of golden hammers. Few of them knew that they were making bad decisions at the time. My favorite early examples include C++ for a team of COBOL retreads, Visual Basic for an inventory and control system, and Lotus Notes for a transactional airline reservation system. With Java, we''ve got a whole new collection of potential golden hammers.
220.127.116.11 JavaJava is one of the biggest golden hammers that you''re likely to wield. You should have many other tools to choose from, including scripting languages and competing languages. Yet choosing alternatives often carries a stigma that it doesn''t deserve. Some industry dynamics are hard for me to understand. Microsoft technologies build richer interfaces with much less effort than their Java counterparts, and many enterprises support nothing but Microsoft clients. Yet even in this restricted environment, most developers would rather wade through the neck-deep quagmire that Swing has become rather than inject any Microsoft development where it makes sense. On the other side of the fence, Microsoft bigots would prefer to tune up that rusting clunker that Microsoft calls their message server and tie it together with 10-year-old transaction code in an unmanaged environment, duct tape, and bailing wire rather than use a better middle-tier technology like one of dozens of Java application servers.
18.104.22.168 J2EEMost applications don''t need J2EE. Sun has effectively carried the J2EE brand into the mainstream. It''s hard to find a simple, standard-edition application server and few customers consider deploying that way. If you''ve ever been tasked with getting a J2EE server off of the ground, you know: it''s a tedious, demanding process under the best of circumstances. On the other hand, if you''ve been fortunate enough to lay out a lot of money to buy a whole fleet of these things, you may have had your vendor install it for you. When you lay out a ton of cash, they work hard to keep you happy. But J2EE is not the lowest common denominator! Many applications should deploy with nothing more than a servlet container, a web server, and a database connection. Some of the finest and fastest commercial web sites use nothing more than Tomcat on Apache.
22.214.171.124 DistributionWhen you''re reading about web solutions, you probably see all kinds of potential clustering strategies in the name of scalability. Customers with larger applications often settle on deploying a cluster of presentation servers, a cluster of business servers, and resource servers. It''s a tried-and-true formula that scales well for large loads, but it''s not the only formula. Increasingly, experts are thinking about how to consolidate these systems to save complexity and communications costs. Often, you can get away with one middle tier cluster. The motivation is simple: when you begin to add distributed nodes, you''re inviting complexity and overhead into your door. You frequently invent the need to connect to named services, manage distributed transactions, and create synchronous and asynchronous messages. I have seen any number of middle tier applications designed with arcane multiobject hierarchies wrapping a single, local database transaction. It pays to occasionally look at every distributed tier with fresh skepticism. You can frequently consolidate individual tiers with potentially significant gains. Figure 5-2 shows two alternatives for consolidating a typical architecture. One alternative is to deploy static content and the MVC framework with the business tier, eliminating the need for a distributed façade. Another alternative is to deploy the CPU-intensive business tiers with a RDBMS, which often underutilizes CPU cycles.
Figure 5-2. Sometimes consolidation of tiers reduces overhead and complexity
126.96.36.199 EJBEJB is not so much of a golden hammer as a glass hammer. The idea may be pretty to look at, but it''s much less impressive in practice. Perhaps no other Java API has been as hyped or oversold as EJB. I''ve written a whole book on the topic; I won''t rehash it here. As the years go by, I spend less time talking about EJB pitfalls and more time talking about when EJB should be used at all. This book is about moving away from EJB in its entirety. Still, certain elements of that framework have a limited value. If you''re going to use EJB, use it appropriately in situations like these: Façades If you have a distributed, transactional façade that needs to be highly scalable, consider EJB. In fact, in its original incarnation EJB supported only stateless session beans, with plans to quickly add message-driven beans. The EJB framework was to provide scalable pools of stateless resources, to control access to scarce resources on higher tiers. Thin wrappers Don''t put too much of your logic inside of the EJB itself. Use the EJB as a façade or a thin wrapper around POJO objects that do the actual work. This design is much more testable and easier to manage. Multiple services Use EJB only for transactional, distributed problems. If you find that your façade layer no longer needs to be distributed, don''t use session beans for it. They''re overkill for a local call. Similarly, don''t use EJB when you only need one token service. Whenever possible, adopt a simpler solution. No entities Avoid entity beans and CMP altogether. Entity beans are unwieldy albatrosses that take tremendous energy to understand, code, tune, and maintain. Better solutions are out there; find them. No stateful session beans Avoid stateful session beans. You''re better off using HTTP sessions or databases, depending on your solution. Those solutions are more broadly adopted and won''t tie you to EJB for the long term. Experienced team Consider EJB only when you''ve got enough experience and skill to deal with the inevitable issues. Don''t kid yourself. EJB requires a lot of knowledge and finesse to pull off. If you don''t have it on your team, get it or use another framework. These are just a few guidelines for using EJB appropriately. But just to reiterate, I strongly believe that the best way to win the EJB game is not to play.
188.8.131.52 XMLFew will argue that XML has changed the face of Java programming forever, but not all of the changes are for the better. XML does solve some problems very well, but it also has serious limitations. XML is hard. If you''re a great programmer, you probably think that "hard" is overstating it. You might prefer "tedious." If you''re new at programming, you may wish that I''d chosen a stronger word: the syntax is awkward, and the many versions often collide. If you''ve ever needed a different version of your XML DOM classes than your JDK provides, you know exactly what I''m taking about. XML does seem to be getting more difficult. As it becomes more sophisticated to solve the demanding problems of the few, it''s rapidly succumbing to the bloat. XML can also be slow. Depending on what you''re doing, it can take a whole lot of time to move those bytes around. Since it''s so verbose, XML takes longer to marshal than other, more limited message formats. XML sometimes forces you to define your data structures too early and too definitively. DTDs and Schema are hard to write and often you end up writing them once, too early in the process, and bound to them for the rest of time. This is one of those coupling-by-decoupling paradoxes: XML Schema is supposed to free us from long-term coupling to a data definition, but in practice, it usually ends up just as restrictive as all other data definition mechanisms. Still, XML has its place. If you value decoupled software and think that messaging models are undervalued and underused, you''ll recognize the incredible benefits XML delivers. It''s flexible, self-describing, and broadly adopted. There''s nothing out there that comes close to it. (Can you see the gold on that hammer beginning to gleam?) These advantages drive XML everywhere, including some inappropriate places. You don''t have to drop that tool like it''s heated up to 400 degrees. Just be careful. XML is just the input, or output, for an interface. To use it appropriately, consider the nature of the interface. XML works well to reduce coupling by providing a standard, self-describing payload for some type of interface. It provides power and flexibility at the cost of complexity and performance. To decide whether to use it, ask these questions: What will a tighter coupling cost? If you''re building a very specialized interface with high performance requirements, it''s perfectly valid to live with tighter coupling in order to reduce complexity. How complex is your message? If it''s not complex, something simpler may serve you well. You wouldn''t consider XML to specify command-line parametersit''s overkill. You may only need a simple text string, or a map of name-value pairs. Both of these message types can be quite flexible and dynamic. On the other hand, your message may be deeply nested, with rich schema requirements. For messages, do you control both ends of the interface? If you do, consider a lighter message payload. If not, XML may allow you to have a message format that''s self-describing, extensible, and neutral. Do you need to bridge programming languages, or enterprises? If you''re working across very different platforms, XML can provide a convenient intermediate representation to let the platforms communicate. Are your performance requirements relaxed? XML requires significant data marshalling. Be sure that your infrastructure and application can afford the increased requirements. If it''s a borderline situation, do a brief proof-of-concepts to be sure. Are you trying to support possible future requirements? If you are, stop. It''s usually better to adopt a simple solution and make sure to build a loosely coupled service that you can adapt to future purposes. On the topic of XML, I''m not religious. I''m a pragmatist. XML is a fact of life. Use it when it makes your life easier; leave it behind when it doesn''t. If you''re a Java programmer, you probably need XML within your bag of tricks somewhere, but you don''t have to reach for it at every opportunity.
184.108.40.206 Persistence frameworksAs the programming craft advances, developers need to think in progressively more complex abstractions. Half of everything that you know will be obsolete in seven years. Your brain is like any other computer: space is limited. When you push a new piece of data insuch as aspect-oriented programmingsomething else is discarded. One of the skills that''s getting progressively harder to find is good database application programming. As a result, many developers tend to reach for persistence frameworks and expect them to hide all of the database details. In fact, that''s what persistence frameworks are designed to do. The problem is that reality gets in the way. Real persistence frameworks eventually create good or bad SQL. Real applications are either good or bad citizens of the database realm. It''s hard to build a persistence framework that solves general problems well for every instance and it takes a knowledgeable database developer to know the difference. Persistence frameworks do have a major tangible benefit. They let Java developers deal with an application in comfortable terms. Java classes, instances, and idioms replace database tables, indexes, and records. Persistence frameworks also have a cost: their abstractions can hide problems, they can be hard to tune, and they may get inexperienced developers into trouble. If you have a complex data model and you''re spending a lot of time wading through endless persistence details, a persistence framework can save you a whole lot of time if someone on your team knows what''s going on under the hood. But don''t use what you don''t understand. If database access is working and the details aren''t overly tedious, you probably don''t need a persistence framework.
220.127.116.11 Web servicesThe web services standard is the latest in a long line of technologies that promise to tie disparate systems together. It was supposed to be simple, fast, and intuitive. One look at the list of acronyms for associated technologies tells us something has gone horribly awry (SOAP, XML-RPC, WSDL, Disco, UDDI, WS-I, WS-Eventing, and WSA). SOAP originally stood for Simple Object Access Protocol but tellingly, they''ve dropped that acronym. Yet you can''t simply ignore web services. With the potential to tie together Java and Microsoft technologies and the strong backing of most of the players in both spaces, web services has a meaningful niche to fill. So far, I''ve had a difficult time understanding what that niche should be. If you look at the basic characteristics of the technology, some ideas begin to crystallize: Relaxed performance requirements The web services API is heavyweight and relatively slow. It''s tough to imagine a credible use for web services with demanding performance requirements. Spanning languages or platforms Java has many better native options. If you''re trying to wrap a Java service for a Java consumer, it pays to check one of the excellent native APIs first, such as a lower-level API like JMS or even RMI, depending on what you''re trying to do. Web services do have strong supporting tools on many platforms, most notably Java and .NET, as well as several others. It''s a strong alternative to link disparate systems, since it''s relatively simple compared to the alternatives. Service model Web services encapsulate a loose-grained client/service model. It should be used accordingly. Trying to use web services for fine-grained communications is asking for trouble. Table 5-1 is a list of the most frequently used golden hammers. It is by no means complete. If you look closely, you can see a pattern begin to emerge. A golden hammer can definitely drive in a screw if you strike it often enough and hard enough. Most of the golden hammers that I''ve listed can do a jobjust not efficiently or well.
|Tool||Suitable for||Not suited for|
|Java||Object-oriented programming Web-based development Server-side development||End-user scripting Rich user interfaces on homogeneous platforms|
|J2EE||Distributed transactional programming Heavyweight enterprise applications||Lightweight applications|
|Distribution||Scalability Controlling access to scarce resources||Simple, lightweight applications Performance improvement|
|EJB (stateless session beans, MDB)||Distributed, transactional façades Secure, distributed transaction monitor||Lightweight applications Applications where transactions are limited to one database Façades that are not distributed|
|EJB entities||Nothing||Sane applications|
|Persistence frameworks||Sophisticated domain model Relational database Moderate performance requirements||Relational problems (e.g., reporting) Simple problems Problems that do not present a domain model Teams without database experience|
|Web services||Heterogeneous platforms and languages Coarse-grained communications Moderate performance requirements||Java to Java applications Demanding performance requirements Fine-grained communications|
|XML||Self-describing data Standardized data format Heterogeneous messaging||Message format when one team controls both the producer and consumer High performance requirements Simple, lightweight applications|