EJB Patterns Training


Published on


This is a slide deck from a presentation on EJB Patterns.

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

EJB Patterns Training

  1. 1. Understanding Patterns Choosing the Right EJB Patterns
  2. 2. Understanding Patterns Speakers Qualifications • Steve Close has been Lead Java Trainer for Intertech Training since 1997 http://www.intertechtraining.com • Author of several Java courses from Java 101 to EJB and Web Services • Published in JDJ magazine (November 2003) • Spoke at JavaOne™ in 2002 on Web Services • Spoke at SD West 2004 and 2005! • Spoke at No Fluff Just Stuff Minneapolis 2004
  3. 3. Understanding Patterns Primary Goal Teach you how to understand why we use patterns and which patterns commonly apply to an EJB deployment
  4. 4. Understanding Patterns Course Objectives • Promote the use of Patterns • Learn why using a delegate can make client mockup easy • Understand how Session Façade reduces the granularity and encapsulate business flow • Figure out how the Service Locator makes finding easier, supports caching and removal of EJB (if you want to) • Understand granularity and how to reduce it with Data Transfer Objects • See how Value List Handlers improve large list performance • Discuss why Fast Lane Reader is use to remove the Entity Beans from some situations
  5. 5. Understanding Patterns Why Patterns? • Patterns provide a few key benefits – Patterns are solutions to problems • Find an existing solution don’t reinvent • Patterns come with proven track records • Patterns list the benefits and downsides – Patterns represent a language • “Pattern speak” can make communicating design much easier for anyone who has learned patterns • Putting a well chosen word (pattern name) to a solution or concept makes that concept much easier to remember • Recognizing a pattern in other people code makes code reading much easier (see earlier bullet)
  6. 6. Understanding Patterns Why Patterns? – Knowledge level of reuse can be more effective than object level • Describing solutions is not new patterns just formalize one way to get it done (standardization) which leads to reuse • All object technologies (and services too) promise reuse, patterns deliver design reuse effectively
  7. 7. Understanding Patterns Why Not Patterns? • If you’re here I expect you’re pro-patterns, but it’s only fair to mention the downside – Pattern language can be intimidating – Pattern “Speakers” often attempt to use the lingo to impress – Patterns are not recommended for programmers until one OOP language is well understood (not for beginners) – Pattern users are often designers or even architects so arguments are common
  8. 8. Understanding Patterns Context • In this lecture we will focus on a few patterns, specifically those commonly encountered in EJB applications – EJB give us a context to talk about patterns, but these patterns can apply in other situations – EJB patterns are really patterns around distributed environments and as such can be applied to any distributed application – There are more patterns available, see resources at the end of talk
  9. 9. Understanding Patterns Business Delegate • The first Pattern we will discuss is one of the first we commonly use when creating a client app for an EJB – This pattern can be found in detail in the “Core J2EE Patterns” Book (ACM) – We use Business Delegate to “Mock” functionality without creation of the EJB
  10. 10. Understanding Patterns Business Delegate • Officially the Business Delegate “unifies client interface” – Many client interfaces can use the same delegate – Business code can change behind the delegate forcing only the delegate to change (avoiding the ripple) • With EJB it is used to with a Session Façade which we will discuss next
  11. 11. Understanding Patterns Business Delegate • Looking at a diagram we can visualize the business delegate (NOT a UML diagram) Client Business Delegate All Remote Calls
  12. 12. Understanding Patterns Business Delegate • Although the official benefit is alluded to earlier there are really common concrete reasons to use this pattern in EJB – The Delegate can have a faux implementation to allow client testing before the EJB application is stable (great for demo and prototyping) – The Delegate can remove the need for a client to understand exceptions providing a single object that “interprets” remote exceptions – The Delegate can cache resources like stubs to provide better performance – The Delegate is owned by the client coders so it can shelter the client side programming from changes to the EJB layer
  13. 13. Understanding Patterns Business Delegate • On the Downside – Duplicate Code – The Delegate is commonly combined with a Session Façade and in simple applications and in first releases the Delegate and Façade can be very similar – This duplication can be annoying and hard to defend, especially if you don’t use any of the advantages the delegate provides
  14. 14. Understanding Patterns Business Delegate • The code for the delegate isn’t all the impressive, but here is a sample of a client using a Business Delegate Member newMember = HttpRequestConverter.getMember(request); if (isValid(newMember)){ MemberTracker delegate = new MemberTracker(); delegate.addMember(newMember); viewHelper = new MainHelper(); }else{ System.out.println(quot;Insert Failedquot;); //... }
  15. 15. Understanding Patterns Business Delegate • The below code shows where the “faux” implementation would be public class MemberTracker{ public void addMember(Member newMember) throws AppException{ //You can either fudge in the add Member, //or implement for real //implementation can change to remote or non-remote }
  16. 16. Understanding Patterns Session Façade • Our second pattern is probably the most commonly referred to pattern for EJB apps – The Session Façade is pattern is describe in full in Core J2EE Patterns (ACM). – A Session Façade is a derivation of the Façade pattern found in the Gang of Four book (see resources) – We use Session Façade to hide Entity Beans and to provide simpler client interface
  17. 17. Understanding Patterns Session Façade • Officially the Façade is a design that gives a simpler interface to a more complex set of functionality – The traditional example is one of a compiler used to expose a much larger set of function like parsing – Façade is probably the most commonly encountered pattern when attempting to integrate two different systems
  18. 18. Understanding Patterns Session Façade • Looking at a simple picture (from GoF) we can visualize the Façade
  19. 19. Understanding Patterns Client 1 Client 2 Facade Service A Service B Service c Service D Service E
  20. 20. Understanding Patterns Session Façade • Peeling back the abstract benefit of Façade and looking directly at EJB applications we can see some primary advantages to Session Façade – Façade is a natural choice to distributed programming because you are merging (at least) two systems – Session Façade allows you to create a more coarsely grained (chunky) interface reducing transactions and remote method invocations – Façade can hide EJBs from the client, specifically Entity beans which are only accessed from a session bean – The client is given a simpler more business friendly interface to the EJB application
  21. 21. Understanding Patterns Session Façade • The Downside is minimal – In some small applications the façade might appear as a duplicate to other EJB’s
  22. 22. Understanding Patterns Session Façade • Looking at a client using the Façade isn’t all the impressive code wise – In the below code MemberServices is the Façade MemberServices services; services = locator.getMemberServices(); try{ services.addMember(newMember); }catch(Exception ex){
  23. 23. Understanding Patterns Service Locator • Service Locator is our next pattern, usually used for caching and can have other benefits – Service Locator can be found in detail in the “Core J2EE Patterns” book, see resources – This pattern can be used to cache and to allow easy removal or addition of EJB
  24. 24. Understanding Patterns Service Locator • Service Locator was described in terms of distributed system so it’s original description is directly what we use it for – A Service Locator is an object that hides the lookup and caching of object (EJB and JMS object are very common) – Hiding the fairly ugly lookup of an EJB or a Queue is exactly what a service locator is used for thus reducing code length (commonly done by those who don’t know the name of the pattern) – The Service locator can also increase performance by providing a cache of the resource you lookup (less lookups) – The Service locator can also become the object that decides whether you are using distributed or local resources
  25. 25. Understanding Patterns Service Locator • The diagram for Service Locator is less illuminating than the code, so we will spend a bit more time on the code • To get a stub or reference to use an Enterprise Bean you end up writing a bit of code Context ctx = //getInitialContext Object o = ctx.lookup(“ejb.CurrInfoBeanquot;); CurrInfoHome home = (CurrInfoHome) PortableRemoteObject.narrow(o,CurrInfoHome.class); CurrInfo info = home.create(); conversionRate = info.getConversionRate(to, from);
  26. 26. Understanding Patterns Service Locator • Each of the steps in the code above is required, and many of them require you to negotiate with an exterior server (costly) – Getting the initial context should be done only once because of the expense of getting it Context ctx = //getInitialContext THIS ISN’T CODE! – The lookup of a Home interface can be hidden to make it faster, reuse code and to hide details Object o = ctx.lookup(“ejb.CurrInfoBeanquot;); CurrInfoHome home = (CurrInfoHome) PortableRemoteObject.narrow(o,CurrInfoHome.class);
  27. 27. Understanding Patterns Service Locator • In many cases the stub to the bean can be cached and reused instead of the stub to the home interface – This saves the more time by avoiding the call to create – For some EJB types this level of caching is inappropriate CurrInfo info = home.create();
  28. 28. Understanding Patterns Service Locator • A service locator will typically end up with many getXYZService methods or a few parameterized methods – The parameterized technique would require the client to know more about what is being returned and to cast the result – The non-parameterized technique requires a larger interface public CurrInfo getCurrInfo() {...} //or public Remote getEJB(String ejbName, Class ejbType){...}
  29. 29. Understanding Patterns Service Locator • Another benefit of the Service Locator is in easy removal of EJB’s because all EJB lookups are centralized to one object – EJB development commonly starts with a remote interface definition – The Remote interface can be implemented locally – By implementing those interfaces locally you can remove the EJB portion of your application – Removal of EJB is not recommended, but in some situations it is the appropriate, in others being able to deploy with and without EJB might be attractive
  30. 30. Understanding Patterns Service Locator • The code for removal of EJB if you implemented a service locator is actually simple and well encapsulated in the service locator – The decision to use EJB can become a flip of a Boolean – If you use a factory to create the resource locator the factory can control that parameter – This can make a change in distributed to non- distributed client a non-code, only properties file change
  31. 31. Understanding Patterns Service Locator public static final String DISTRIBUTED = quot;EJB“; public MemberServices getMemberServices(String mode) throws ServiceNotAvailableException { try{ if (DISTRIBUTED.equals(mode)){ return getRemoteService(); }else { return getLocalService(); } }catch(Exception ex){ throw new ServiceNotAvailableException(/*...*/); } }
  32. 32. Understanding Patterns Transfer Objects • Transfer Objects are objects that are used to hold (encapsulate) data so the data can be passed between systems – The Transfer Object was described in “Core J2EE Patterns” but originally was named “Value Objects”
  33. 33. Understanding Patterns Transfer Objects • Data Transfer Objects have direct benefit to EJB and all distributed development because the allow you to create more coarsely grained interfaces – One best practices of any distributed system is “Make the Interface Chunky” or coarsely grained – Because each call to a distributed system must be translated to be transferred over the wire (Marshaled) and any network traffics take much more time than local traffic, you need to minimize the number of distributed calls – The use of Transfer objects applies to EJB and any other layer communication (included web services)
  34. 34. Understanding Patterns Transfer Objects • To compare a coarse and fine grained interface we can see a very simple example public interface Account{ public String getCustomerName(); public Address getCustomerAddress(); //... Any other customer info could get a get and set } //vs. public interface Account{ public Customer getCustomer(); }
  35. 35. Understanding Patterns Transfer Objects • The value of a more finely grained interface is user acceptance, but the more coarsely grained interface become valuable by reducing remote method invocation • This Transfer Object concept can be used in many situation (any remote system) – If you are calling into a Database Access layer Transfer Object can reduce the calls to the DB – If you are writing web services transferring large data few times might be preferred – In any EJB client they are appropriate and commonly use within a Session Façade (which also serves to make a chunky interface)
  36. 36. Understanding Patterns Transfer Objects • The most significant downside on Transfer Objects is latency – If you use a transfer object you call the remote system or DB only once saving time – If you continue to call for information out of the Transfer object that data might be stale • The only other compliant I’ve heard on Transfer objects is duplication of types – You might have an Account Entity Bean and an AccountXFer to make calling that entity be less frequent
  37. 37. Understanding Patterns Transfer Objects • The code for a Transfer Object can look as simple as a Java Bean with getters and setters – That should make sense because you’re replacing many getters and setters with one getter/setter pair public String getFirstName(){ return firstName; } public void setFirstName(String firstName){ this.firstName = notNull(firstName); }
  38. 38. Understanding Patterns Value List Handler • The Value List Handler has become a common EJB pattern due to a fundamental weakness in Entity Beans – Value List Handler can be found in more detail in Core J2EE Patterns – Helping Entity Beans is not the only time the Value List Handler should be used – You should understand why this pattern is used and why it comes up when talking about EJB
  39. 39. Understanding Patterns Value List Handler • It is very common for users to query a large list of data – This data can be very large and is not suitable to be transferred in a single remote call – The data is commonly thrown out before the user scrolls through all of the data – The data is commonly read only – One situation where this is true is a catalog or product list, although many situations exist
  40. 40. Understanding Patterns Value List Handler • Entity Beans fail to perform well in these common situations using their findBy methods – The findBy methods have no built in ability to return a subset of the total results – The findBy method calls have varied performance based on vendor implementation – The findBy returns remote references to entity beans which are not read only
  41. 41. Understanding Patterns Value List Handler • Creating a value list handler is a common way to solve these problems – The Value list handler uses the data access layer to query for a series of objects – The Value list can cache the values of the query or the result set, returning a reasonable number of objects – The value object can be set up as read-only object which fits very common situations
  42. 42. Understanding Patterns Value List Handler • The downside of Value List Handler – On the downside you have latency, any data cached can become latent, but that is a common trade off
  43. 43. Understanding Patterns Fast Lane Reader • The Fast Lane Reader pattern is another pattern tightly related to Value List Handler – This one is mentioned to clear up what it is used for – Fast Lane Reader is the pattern of skipping the EJB Layer and the transaction when reading large blocks of data – The Value List Handler commonly uses the Fast Lane Reader to get the job done, then provides the client a pleasant interface
  44. 44. Understanding Patterns Conclusions • Distributed Programming has a few fundamental rules of thumb (best practices) – Chunky not Chatty interface – Distribute what is needed not everything – Layer your applications using interfaces – Possibly - prefer stateless over stateful • Nearly all patterns described are formal solutions that seek to follow these rules
  45. 45. Understanding Patterns Resources • When working with a pattern I suggest typing the pattern name into your favorite search engine – Patterns are well represented on the web • When working with patterns you should be seeking to copy someone else’s solution not reinventing the wheel • EJB has been around long enough that the problems encountered using them have already been solved, look around for the answer
  46. 46. Understanding Patterns Resources • Books: • “Design Patterns” – Gamma, Helm, Johnson, Vlissides • “Refactoring: Improving the Design of Existing Code” – Fowler, Beck, Brant, Opdyke, Roberts • “Core J2EE Patterns” – Alur, Crupi, Malks • “Patterns of Enterprise Application Architecture” - Fowler • Web Sites: – http://hillside.net/patterns/ – http://martinfowler.com/articles.html#N30 – http://c2.com/ppr/index.html – http://java.sun.com/blueprints/patterns/
  47. 47. Understanding Patterns Presentation Complete • If time allows: questions • Stop by the booth, something must be free today • Check out www.intertechtraining.com