The Big Moose Saloon Question and Answer of the Month

Mosey on in and pull up a stool. The JavaRanch Big Moose Saloon is the place to get your Java questions answered. Our bartenders keep the peace, and folks are pretty friendly anyways, so don't be shy!

Over in The OO, Patterns, UML and Refactoring Forum, Dan Malks did a heck of a job giving folks some good advice on the ol' "to bean or not to bean" decision. Following is an excerpt from the original forum thread.

Question: To bean, or not to bean, that is the question.

Answer: A good question to ask yourself is "what are the requirements of my app (functional and non-functional)" and let these answers drive your architecture and design.

As for serializing your object, do you need to transfer information across a physically distributed boundary? ie: is your biz tier remote from your presentation tier? This is one reason you would want to serialize an that you can use it to transfer data across this distribution boundary to reduce the sort of network performance problems that can arise with distributed object invocations. This pattern is called "Transfer Object" and is typically used in J2EE when you are using EJB in a remote biz tier. In this case, you would use a remote Service Facade, called a "Session Facade" to serve as a uniform, course-grained access point into your remote services.

If you do not have a remote business tier, you can still use EJB, using Local Session Beans as your Service Facade for the same purpose. Using Session beans in this way gives you the benefit of using their transaction semantics and declarative security. If you don't need these features, then you can use a Plain Old Java Object (POJO) Service Facade, foregoing the use of EJB entirely. Lots of different options.

Either way, your Service Facade should delegate to Application Service(s) (another pattern), where your common service code resides. Application Services work with Business Objects, which represent your domain model (such as Company in your case).

Question: Should I create a separate class for my db transactions?

Answer: There are numerous approaches to persistence. Separating your data access logic from your Business Object and moving it into a separate class as you suggest is described in the "Data Access Object" (DAO) pattern. There are many other options, as well.

We cover all this information in detail, including design tradeoffs and code samples in our book Core J2EE Patterns, 2nd ed.

Remember, use patterns as a guide and use what works, but don't feel compelled to use a pattern "just because it's there". A pattern is a tool, just like any other and should be used judiciously and appropriately.