Sunday, February 14, 2016

EJB Good Practices

EJBs abstract your middleware or business logic layer. They are transactional in nature so when you hit your persistence layer (mostly through JPA), the transaction is already there for your database session. As a result, all DB operations are going to complete or none of them, i.e. EJB operation is atomic. Let's cover some of the good practices:

Don't create EJB methods for CRUD operations

Imagine creating operations in your EJB for creating, fetching, updating or deleting your entity. It's not going to serve the purpose; quite clearly, CRUD operations are not your business logic!

In fact, CRUD operations will be part of your more sophisticated business operations. Let's take that you want to transfer x amount from a bank account A to another account B. There should be just a single method which reads appropriate records from DB, modifies them and performs the update.

Also, creating a CRUD operation gives the impression that EJB is created for each entity. We should create EJB for a group of related problems like manage accounts, policy manager etc. You can abstract your CRUD operations in Data Access Layer though!

Minimise Injecting EJBs in the Presentation layer

Imagine yourself working in the presentation layer (Servlets, web services, ..) and having to deal with multiple EJBs to delegate the call. You are going to struggle to find appropriate EJB and then a method for delegating the incoming calls.  Especially when someone else is taking care of business layer!

This is going to defeat the separation of concern principle which is important to manage your complex distributed system. So what's the solution to deal with this - Bundle related EJBs in a single (super) EJB and inject this super EJB. 

But make sure that, in doing so, you are not putting un-related EJBs together just for the sake of minimizing the number of EJBs.  Each EJB (including super) should adhere to the single responsibility principle

Reusing EJB methods

Suppose you have quite complex use cases which resulted in a big EJB class definition. So, the obvious question would be, how do you achieve reusability with EJB methods?

Just like a normal Java class, you can create helper EJBs with reusable methods. Multiple EJBs can use the services provided by this helper EJB. And to make these helper utilities more clear, you can put this in a utility or helper package inside your main EJB package. 


References

---
would love to hear your suggestions/feedback about this post.