Welcome to the Jumble - J2EE best practices

Discussions

News: Welcome to the Jumble - J2EE best practices

  1. Over the last five years, a lot has been written about J2EE best practices. There now are probably 10 or more books, along with dozens of articles that provide insight into how J2EE applications should be written.

    In fact, there are so many resources, often with contradictory recommendations, navigating the maze has become an obstacle to adopting J2EE itself.

    To provide some simple guidance for developers entering this J2EE Jumble, this article sets out to compile the following "top 10"(actualy 12) list of what are the most important best practices for J2EE.

    Top Ten List

    1. Always use MVC.
    2. Apply automated unit tests and test harnesses at every layer.
    3. Develop to the specifications, not the application server.
    4. Plan for using J2EE security from Day One.
      Build what you know.
    5. Always use Session Facades whenever you use EJB components.
    6. Use stateless session beans instead of stateful session beans.
    7. Use container-managed transactions.
      Prefer JSPs as your first choice of presentation technology.
    8. When using HttpSessions, store only as much state as you need for the current business transaction and no more.
    9. In WebSphere, turn on dynamic caching and use the WebSphere servlet caching mechanism.
    10. Prefer CMP Entity beans as a first-pass solution for O/R mapping due to the programmer productivity benefits.
    Read The top 10 (more or less) J2EE best practices
    What would be in your top ten list? What is wrong with this list?

    Threaded Messages (27)

  2. Coarse grained objects[ Go to top ]

    I would say, use Entity beans only for Coarse grained objects
  3. Prefer JSPs as your first choice of presentation technology.
  4. I disagree with that point. I would rather say the opposite- disregard JSP and look for a beter Web framework, like Tapestry, that does a better job in separation of roles and layers in web application and offers true promotion of reuse of components. I've come to learn the hard way that any framework that incorporates anything other than HTML in pages is a bad idea. And JSP falls certainly in this category.
  5. 1. Sure. One of the most important things in comlex aplications is to use MVC.

    6. I think the problem with Stateful session beans is to use them well. But they have the same problems that HttpSession ir they are fully loaded with megs of data. So the same things applied to httpsession can be apliied to stateful beans and they will work well,.. (I think :) )

    anyway, I think this article repeats everything said before about best practices, nothing new,...
  6. JSP and web frameworks[ Go to top ]

    JSP is not a framework like tapestry.

    JSP can be horrific to work with if done badly, which has to be said is usually the case. But if implemented properly there is nothing wrong with using JSP in your J2EE project as long as it is the best option for you.

    Instead of saying x is better than y, how about weighing up the pros and cons of x/y and then use what is best for you and your project.

    There is too much JSP is this, Tapestry is that and Struts doesnt achieve this that or the other! Certain jobs are best acheived with certain tools, just find the right fit for the job and budget and timeframe.

    Cheers

    G
  7. CMP?[ Go to top ]

    (is recommendation 10 -- "prefer CMP for O/R mapping" -- flame bait?)

    If you're going to recommend CMP then it seems like you also need to recommend CMR, to help avoid "application joins".

    For the record, however, I've not noticed any productivity gains that follow from using CMP (or BMP).
  8. O/R[ Go to top ]

    <blockquoteFor the record, however, I've not noticed any productivity gains that follow from using CMP (or BMP).I have found CMP a lot easier to code if that's what you mean. I have also found that any non-trivial application benefits greatly from some type of O/R mapping. Although I am somewhat partial to Hibernate.


    Still, CMP has some nice features even against Hibernate since part of making Hibernate easier for myself and my developer was building in a Facade with names like findByPrimaryKey, findAll, etc.
  9. 0. Learn the difference between a transaction and a distributed transaction. If you are building a web site with a database backend and simple transactions, you better have a conmpelling story for why you need EJB.

    1. Always use MVC.
    Use a framework like Echo where MVC is inherent.

    2. Apply automated unit tests and test harnesses at every layer.
    Think hard before adding a useless layer (read EJB). You will have more tests for more layers that get you no closer to finishing your app. With every layer and test you introduce new bugs. Unless you have a distributed transaction you probably don't need EJB, and Entity Beans have no valid application. EB is garbage. Read the RUBiS benchmarks.

    3.Develop to the specifications, not the application server.
    Use the best frameworks that work in the real world. Don't believe the bs in the books that tell you J2EE is a best practice for *most* client/server apps.

    4.Plan for using J2EE security from Day One.
    Build what you know.
    "build what you know" ??? what does that have to do with J2EE security? If you want to easily manage single sign on, check out a portal server with support for the Portlet JSR.

    5. Always use Session Facades whenever you use EJB components.
    Also read as "Don't use EJB unless you have a distributed transaction."

    6. Use stateless session beans instead of stateful session beans.
    This is still debated.

    7. Use container-managed transactions.
    You are sure you have a distributed transaction, right? Otherwise, what the heck do you need a container to manage?

    8. Prefer JSPs as your first choice of presentation technology.
    Funny, because JSP programming is completely at odds with MVC (#1 on this list) unless you wrap a framework around JSP. If you are a Java programmer, prefer a framework that leverages your ability to write code, not markup scripting languages. Try Echo or the like.

    10. Prefer CMP Entity beans as a first-pass solution for O/R mapping due to the programmer productivity benefits.
    Huhhh? Why the heck would you use an Enity Bean? It totally breaks object-oriented programming. Finder methods that can only return a single concrete subclass? Local interfaces that prove the entire idea behind entity beans was broken? Enity beans have *no* place in any application. It has taken a long time for people (including me) to come to this realization in the face of all the "best practices". Try a framework that is meant for Object Persistence (JDO, Hibernate, etc.) and object/relational mapping.
  10. I think the purpose of the article is not to help you determine if J2EE is relevant to your project or not. The purpose is to promote best practices for those who chosed J2EE as a framework for their project.

    Having that in mind, I know that all best practices are good because I use almost all of them to a great success. There may be some arguments against a best practice but the good stuff it brings exceeds the not so good stuff.
  11. The purpose is to promote best practices for those who chosed J2EE as a framework for their project.
    I think the definition isn't correct: "J2EE being a framework".

    J2EE is not only EJB spec. My Struts application is a J2EE application because it uses Servlets and JSPs. So, yes, you can use JSP/Servlet/Struts/Hibernate in a "J2EE project". One doesn't have to use EJBs to get a J2EE label.
  12. 0. Learn the difference between a transaction and a distributed transaction. If you are building a web site with a database backend and simple transactions, you better have a conmpelling story for why you need EJB
    I think you summed it up quite nicely. Your 10 best practices are better than the 10 in this "news" article.

    J2EE = App Server vendors income

    -Michael
  13. 0. Learn the difference between a transaction and a distributed transaction. If you are building a web site with a database backend and simple transactions, you better have a conmpelling story for why you need EJB
    I think you summed it up quite nicely. Your 10 best practices are better than the 10 in this "news" article. J2EE = App Server vendors income -Michael
    Again, the question now is not if J2EE is relevant or not for your project but 10 best pratices to put in place for a project that fits J2EE. I agree that for small project, J2EE is often not the best framework to use, but it is not in question here.
  14. Why a top 10 list?[ Go to top ]

    Again, the question now is not if J2EE is relevant or not for your project but 10 best pratices to put in place for a project that fits J2EE. I agree that for small project, J2EE is often not the best framework to use, but it is not in question here.
    OK, so if I need a small web project, I shouldn't use J2EE. So what should I use? I can't use Java because servlets and jsp are part of J2EE. I guess I could buy a very expensive portal product and use portlets (or find an open source portal product), but I might not need a portal. I just want a small web app.

    J2EE is not EJB. Quite a few of us use J2EE fine without EJB's and think that any best practice that says you must use EJB should be questioned...

    J2EE is not EJB.

    Oh, maybe I forgot to mention: J2EE is not EJB.

    Perhaps if you need to make this list, you need to add a disclaimer to let people know what small subset of projects it applies to. Your top 10 list won't work for the applications I write.
  15. Why a top 10 list?[ Go to top ]

    I certainly know that J2EE is not EJB. That's why I think that if you choose to code JSP-servlets, you decided to choose J2EE and then all 10 best practices applies. For small sites I would consider either PHP which provides a lot more then JSP for simple low volume sites or a no code solution with a content management system. I think that a lot of small project done in J2EE could be easily done with Jboss-Nuke, Jahia (www.jahia.org), etc.
  16. J2EE still isn't EJB[ Go to top ]

    I certainly know that J2EE is not EJB. That's why I think that if you choose to code JSP-servlets, you decided to choose J2EE and then all 10 best practices applies. For small sites I would consider either PHP which provides a lot more then JSP for simple low volume sites or a no code solution with a content management system. I think that a lot of small project done in J2EE could be easily done with Jboss-Nuke, Jahia (www.jahia.org), etc.
    I think you are being a troll, but I'll bite.

    Why should I be forced to use EJB if I want to use servlet/jsp in my application?

    Do you think that if someone builds an application in php they have to use every php module? If I have to use EJB in every J2EE app, am I required to use JMS? php isn't a viable option for enterprise applications in my environment. You obviously have never tried to compile php to work with oracle. With java, I just include a jar in my WEB-INF/lib and Oracle connectivity works. Also, in my company, Java is the standard language.

    I'm going to quit arguing with you now. You obviously build quite different applications from our company. I'll keep using J2EE without EJB and my applications will continue to be successful.
  17. Bes Practice Redefined[ Go to top ]

    I agree,

    Very often, project teams decided upon the technology, (or have it imposed) before they analyse the system requirements. Best practice is solving your problem using the most "apppropriate" technology. The Agile development manifesto warns against over engineering, and suggests that we should find a minimal solution that meets todays' needs.

    Having built several "heavy weight" J2EE apps, and seen very little value gained from the (over) use of "industrial strength" containers, I tend to agree. All that overhead for very little pay back.


    Why do project teams continue to do this? I can only put it down to fashion and marketing.

    My list:

    1. Understand your requirements
    2. Avoid a container soln if you can
    3. Use containers sparingly where you must.
  18. 5. Always use Session Facades whenever you use EJB components.Also read as "Don't use EJB unless you have a distributed transaction."
    I have had very odd experience with distributed transactions. I mean, you should never assume that using XA instead of local ones will magically solve everything related to sync different resources.

    Namely:
    1. There are a lot of not-so-obvious things to tweak and pay attention to (e.g. if your database is Oracle you must install Java support)
    2. XA transaction being stuck and half-done (because of what turned out to be a bug in HPUX JVM) effectively blocks all database updates and in the end system loses much more data than it would do if transaction was just local one. And yes, that was a production site...
    3. Performance penalty is at very least 50-100%, mostly on database side.

    Unless your application deals with very precious and mission critical data and unless all components involved in distributed transactions (J2EE container, JMS provider, database) are well understood by development team, you should never use them.
    Instead you might as well consider one of resources primary (e.g. database) and others transient (e.g. JMS) and provide intelligent business-level recovery scenarios carried out by user-friendly interfaces.

    Unfortunately there are rather stubborn J2EE containers (like WAS) that just throws an exception when you try to use local JDBC resource from MDB being in container-managed transaction. No way man, only XA will go. And if you don't want XA because of a host potential problems with it, then well, you have to resort to ugly workarounds or (yes I dare to say that!) just manage transactions yourself... at least it will work on all containers.
  19. Timur,

    I like the subject of your post and I'd like to pull its cover a little bit more toward the business component layer away from the database.

    Distributing the business objects.

    Currently, we're facing a requirement on standardizing our approach to the security infrastructure and building application living on 3 physical layers separated by firewalls. According to that, the presentation layer (up to the business delegates) is deployed on a Web Container. Across a firewall, the business components should be deployed. Those components access the database through another firewall. We're facing a situation where we have to distribute the components/logical layers of our application. The most intuitive way to achieve that is to use EJBs. At least SLSBs (I don't want to get into a sadistic discussion in tearing apart Entity EJBs over and over again).

    My point is, if one needs to distribute its application, the natural choice is to use EJBs.
  20. Actually my post was a little bit on another subject, namely distributed (XA) transactions, whose entire purpose is to orchestrate simultaneous updates on more than one physical resource (e.g. JDBC database(s) and JMS provider(s)). In other words, as JMS message comes with say purchase order in it, it shouldn't be considered 'consumed' unless all data is properly commited to database.
    My point was that while XA does do what it supposed to do, it might create even more problems than it solves, and should be applied in very cautious way.

    As to distibuting for security: by setting up different layers separated by firewalls you do achieve that your database it at least behind two firewalls from the web layer. So if your frontend server with web app is compromised, there's still a long way to go to real data.
    However, if the whole point is to separate 'public' functionality(i.e. open for all Internet) and 'internal' functionality (content backend, order management, etc.), I would do just two separate applications, probably sharing most of common codebase.
    But anyway there's no common approach that will suit 100% cases. For example, if building on a lot of cheap (==Intel) hardware is not an issue, I can think of a couple of frontline servers running rather simple web apps, sending requests and receiving responses (as ObjectMessage's) via (clustered) JMS. At the other side there will be a battery of (clustered) MDBs who in turn are working via one or another persistence layer on database. So out of all J2EE you'll be effectively using only JMS and Servlets. And by the way you'll scale this up as long as your database server stands.
  21. Add MDA on the top[ Go to top ]

    The first thing to add:

    0. Add MDA "model" on the top of your development process. And use a good structure of your application and components like "specification", "business", "presentation", "test", ...

    An example of this learning process can be seen here:
    http://ejosa.sourceforge.net/ejosa-images/ejosa-template-process-matrix.jpg

    Cheers,
    Lofi.
  22. Stupid[ Go to top ]

    Some of these "best practices" are bad practices.
  23. Best Practices My Foot![ Go to top ]

    More like "WebSphere EJB Practices", and probably not all of them are best in that respect, either. And there's more than 10 practices in there, too, (see #4 and #7, and the author has noted as much) so the author has obviously gone out of stated scope and implemented too much and is trying to save his bacon. Either it's 10 or it's not (unless one is counting-challenged).

    That tends to happen with EJBs... But it's usually a good way for a consultancy/services company (like, oh, say, IBM?) to ask for more money (either before the sale or when it's running late) since there's more complexity and (supposedly) more benefits due to it's "Enterprise" nature.

    #3 isn't a catch-all, either, as I've had several times where I wrote to the API and servers STILL behaved differently. And why should we be forced to use a JCP-approved persistence spec if something better exits? Why not evaluate the possibilities against the design and intended architecture and use of the software?

    #9 doesn't address the varous other options available. I didn't think there were all that many people actually using XML/XSLT to create their HTML pages, so this point is probably being marketed to a very small audience.

    All that said, there's still some good nuggets to be gleaned from the article. Overall I can't grade it better than a 'B-', and that's only assuming you use or have an interest in EJBs and WebSphere.
  24. My personal rules:

    1. Only use session beans when you need to provide remotely accessible services. You may find you only need a servlet engine.

    2. Use an ORM tool -- JDO or Hibernate for instance, instead of entity beans. This performs better and is faster to implement, and you end up with a better object model.

    3. Use a component based web interface framework, like Tapestry or WebObjects in preference to JSPs. These frameworks abstract away the mapping of parameters and the encoding of URLs.

    4. Only use J2EE security if your security model is very simple and coarse grained. Security should be part of your business rules, not part of your deployment!

    5. Don't use WebSphere -- free solutions are just as good ;-)

    Tom
  25. #5 Always use Session Facades whenever you use EJB components.

    I use classes (Called 'accessors') that are serializable as facades. Why should I prefer session beans as a facade?
  26. ...I use classes (Called 'accessors') that are serializable as facades...
    Why do you want to serialize your façades?
    At the end of the day, if they do the same thing, façade or accessor, then the name doesn't matter...
  27. Reality check[ Go to top ]

    A few comments, based on my (sometimes painfully gained) experience:

    The number one thing of all projects, and especially in J2EE, I think, is to establish a working runtime and development environment, that is:

    * Development platform and language - Check

    * Deployment platform/product - Sure, in J2EE you develop to a standardized API, but IRL, a couple of important features will always be up to the specific vendor to provide. Take for example deployment tools, administration and versioning. Sure again, we have JMX etc. to provide the foundation, but in the end, you will be deciding upon functionality beyond the specs, whether you like a certain UI (graphical or console based), etc. - basically, things that makes your life easier and the overall system more stable and, at the same time, adaptable to change. Then again, everything comes at a price. It might be that you don't need all the fancy features that the big guns provide, and even so that only some smaller, potentially OS, vendor provides exactly the functionality you need. Good for you. Whatever the case, the bottom line is _know_your_application_server_ (or whatever product is involved), which I think is a very good real life adaptation of/complement to the "Develop to the specifications, not the application server" advice.

    * Development platform and build system - This, I believe, is a neglected area. A lot of experienced developers set up their Ant (or Maven if you will) build files to accomodate their immediate needs and add functionality as they go. Sure, it might work, but in the least inoptimal case, we have a non-standard, non-documented build system that everyone patches now and then, and within a couple of months time, no-one can or will assume responsibility for it. So, my second main point here is: Establish a working, adaptable build environment by putting in extra up-front effort to accomodate for hierarchy, pluggability, testing, contiuous integration, app server integration and control etc. I am not going to go into the merits of specific build systems such as Ant or Maven, suffice to say that neither of them is a silver bullet. Even though they provide structure (Maven possibly more than Ant), they are no guarantee for a successful build system implementation. As with everything else, a considerable amount of design and maintenance effort are needed, as is an organization that can assume responsibility for its maintenance.

    * Software architecture and J2EE technology choices - To me, J2EE seems to be going through a painful transformation process, where the old king in town - EJB and the closely attached "heavy-duty" API:s: JNDI, JTA, ... - are being challenged (and possibly (partially) replaced) by lightweight APIs and containers. Going the EJB road is no longer the obvious choice (which the author of this article seems to think, or at least take for granted), which, in a way, leaves developers in a void. What should we use instead - Hibernate, JDO, Spring, XContainer, ...? No easy or clear-cut choice, but these aspects (no pun intended ;) might be indicative:
    - Choice of deployment platform and the vendor's commitment to the product. Then again, the choice of technology might be more of an indication of what platform/product to use
    - Experience in the project group with certain technologies and APIs
    - Budget (duh)
    - Big or small organization
    - etc.

    Then again, given a non-traditional choice of a lightweight container, POJOs, and so forth, are we still talking "J2EE"? Do we care...?
     
    To conclude, I think that the article falls into the same trap as many discussions in the "hardcore Java" field do. We start with deciding upon the details before we have the fundamentals in place. Granted, the focus of the article might be narrower than mine, but then again, the title should have been "J2EE Design and Programming Best Practices". To me, J2EE (given that one of the 'E':s stand for "Enterprise") is a lot more than that.

    Cheers
    /Par
  28. I would say that one of the most important rules in J2EE is:<br>

    Dont forget the network: always use coarse grained remote API calls to minimise network chatter. This includes things from UI design, web to business tier, database interactions etc


    regards, <br>
    Nathan Lee
  29. # Use JSP for the presentation Layer

    I completely DISAGREE with this best pratice. Gone are the days when the presentation layer is simply a dumb layer doing no processing/ minimal processing(Writing JavaScript for vallidations!!!!)....Have anybody used Macromedia Flash as the presentation layer. Not only does it gives the desired presentation values it also buffers it up with some flashy graphics (Of Course, If you choose to!). A Flash client acts like a THICK client but has a capability to run on the browser just like any THIN Client. It can communicate to any of the server side programs (Like Servlets, PHP. ASP) thru its XML Sockets code, which needs to be coded in Action Script (Syntactically similar to JAVA) and transfers data to and fro using XML....isn't this great....

    Flash, however also has different mechanisms by which it can directly connect to the EJBs....called Remote <something> I forgot!!!


    Cheers,
    Manjunath