Better Faster Lighter Java [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

Better Faster Lighter Java [Electronic resources] - نسخه متنی

Justin Gehtland; Bruce A. Tate

نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
افزودن یادداشت
افزودن یادداشت جدید









5.1 Golden Hammers



In 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 Allure



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



5.1.1.1 The sales process



Other 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


Here''s a little more detail about each step:



Prospecting




The best salespeople make hundreds of phone calls and mine their
customers for leads. The goal is to establish an interest in their
product. Once the salesperson has established interest,
she''ll try to get to the decision maker.
That''s called getting to power. The final step is to
establish that the customer has the budget to buy the product. If
you''re a serous buyer, don''t share
your overall budget with your vendor! They''ll use
that information against you.




Securing sponsorship




Sales reps know that sales involving an inside sponsor (usually
called a power sponsor) are
more successful because there''s no trust barrier to
overcome. It''s often a good relationship for both
parties. If you''ve already decided on a technical
solution and you''re trying to sell a technical
solution to your management, you can use your role as a power sponsor
to get your vendor to do a lot of your legwork for you. Chances are
good that they have much more information.




Getting agreement (pre-close)




The sales rep comes in, buys lunch, and slings around some nice
coffee mugs and cool pens. In the relationship stage, the salesperson
wants to build up a level of trust. In the relationship building
stage, the sales rep tries to get a list of objections. Their goal is
to get you to agree to buy the software once they overcome all of
your objections.




Execute (technical sales)




Armed with a set of objections, the vendor passes control of the sale
from the rep to the technical sales team. The sales team can take a
number of different approaches, all designed to overcome your
objections and make the sale. They may include one or more of these
elements:



Technical presentations. Use these to your
advantage. Let your vendor answer critical questions about their
product. Be careful, though: the vendor is not the best source of
information about their competition. (In fact, while I was at IBM, I
found that certain vendors were notoriously bad.)



Proof-of-concepts (POC). This is the sales job
that I did at IBM. POC engagements are expensive. A vendor may do a
POC if you say you''ll buy if it''s
successful, if they believe that it will improve their odds of
closing the deal (usually, based on some competitive advantage), or
if they believe that you won''t buy without one. Once
you''ve come to a tentative decision about a vendor,
get proof that the product works. Pay if you must.



References. Reference selling is increasingly
taking the place of proof-of-concepts. Be cautious here, too. Hearing
a name at a vendor meeting is not the same as talking to the
customer. You''ll also want to know if the customer
received any special consideration in exchange for the reference, and
if they got any special support to make a project go smoothly. Unless
you also agree to be a reference, you may not get the same support,
so take references with a huge grain of salt. Further,
don''t buy without a reference that you trust.





The close




Once you''re at the end of the process, the vendor
closes you. If you''ve got special negotiators at
your company, it''s best to take advantage of them.
If you don''t, then it may pay you to take advantage
of a negotiating class. Your sales rep probably has.





That''s what you''re up against. You
can use the sales process as a source of information to make a
knowledgeable decision. You should use them to help you fully
understand a particular product and areas in which the vendor
believes it has an advantage. Just don''t use the
sales process as your only source of
information. And above all, don''t make buying
decisions based on friendships with sales reps! If you do either of
these things, you''ll find a toolbox full of shiny,
expensive golden hammers.



5.1.2 Some Examples



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



5.1.2.1 Java



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



5.1.2.2 J2EE



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



5.1.2.3 Distribution



When 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


The image in the center of Figure 5-2 represents
many typical deployments. However, by deploying the façade
layer next to your MVC framework, you can eliminate the need for a
distributed façade. One client of mine did so and at the
same time eliminated the need for a J2EE server by eliminating the
need for stateless session beans.


Another strategy (the right-hand side of Figure 5-2) shows the
deployment of
business-tier logic with the RDBMS. This deployment solves three
major problems:



Typical well-tuned RDBMS servers rarely use more than a small
percentage of CPU cycles. Deploying a CPU-intensive business tier can
take advantage of those extra cycles for intensive data marshalling.



The communication costs between a database tier and a business domain
model can be among the most expensive in an entire application.
Deploying them together alleviates this concern.



Security is harder to manage across a wire than locally between
processes.




Think about it like this: it takes a great deal of energy to confine
your business domain model to the middle tier. Some of the logic
inevitably wants to fight its way to higher or lower tiers.
Presentation logic needs frequent access to validation; a persistent
domain model has a tight affinity with the database;
façade layers are much simpler to code and deploy as local
interfaces. If your situation seems to require a deviation from the
norm, don''t fight it.



5.1.2.4 EJB



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



5.1.2.5 XML



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



5.1.2.6 Persistence frameworks



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



5.1.2.7 Web services



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




Table 5-1. Java''s most common golden hammers


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



The list of golden hammers is not complete. They do have a few things
in common, though:



Sweeping integration




Integrated frameworks and platforms claim much, but
don''t always deliver. Attempts to solve more than
one problem can break down if a framework is not easy to extend or
adapt. It''s just too hard to predict in advance
exactly how a multifaceted framework will be used in every instance.




Design-by-committee




EJB, web services, and CORBA were collaboratively designed
frameworks. They were also released before anyone had any real
practical experience with them. Frameworks designed by committee are
especially prone to problems. The open source model works because
visionaries prove their designs under the strain of real-world
problems. Most people don''t understand that most
open source projects fail. This is natural and healthy.




Older frameworks




In the early stages, even sound frameworks can become bloated and
lose their value. While XML has unquestionably added some useful
capabilities, its practical utility is diminishing because
it''s getting too hard for the everyday programmer to
use. Web services seem to be taking this path as well.




Complexity




There''s a time and place for complexity and
you''ve got to balance a healthy tension between
power and complexity. As a rule, watch out for increasing complexity.





It isn''t always true that where
there''s smoke there''s fire. In
fact, you can come up with counter-examples for each of these warning
signs. My point is that frameworks and platforms, like code, can also
smell bad. Develop your instincts, hone them with data beyond the
latest marketing hype, and develop sources that you trust.


I''ve given you a few examples of golden hammers and
other frameworks that I don''t like. While these
warning signs might steer you away from bad decisions, they
can''t help you make good ones. In the remainder of
this chapter, I''ll tell you some techniques
I''ve used to help my customers choose a good
foundation.



/ 111