Monday, October 1, 2007

Architectural Pattern - Layering Enforcement

There are times in just about any Software Architects’ or Lead Developers’ careers when they wish that they had enforced a pattern more effectively – usually this comes when they find some code that has been around for ages that, for example, accesses a Data Access Object directly from a Servlet, a JSF Managed Bean, or (*gulp*) a JSP page… It usually leads to about a week of brainstorming and discussing ways to do better code reviews, and promises that each line of code will be painstakingly inspected before each commit – usually these efforts fall flat before long…

Before I go any further, let me make it clear that nothing can take the place of solid processes that include code reviews at every level, but let’s face it, we don’t all have an infrastructure like Google that will support this level of rigor – in these cases, we’ll take all the help we can get, and there are ways that we can both prevent the situation listed above, and (more importantly) remind the project developers to think about what they’re doing before it's done… That’s primarily what the following Architectural Pattern is about – a little technical help to try and keep things in line until someone gets a chance to do that code review…

So here I present the Layering Enforcement pattern, the purpose of which is to help ensure that certain classes, or types of classes are only called in certain situations… there could be many places where this will be useful in a given project – the example that follows involves a situation where the Generic CRUD Components from a recent blog entry by Adam Bien should only be called by Repository classes, so that database access is confined to places where it is expected, rather than spread around the classes in the project…

Many different implementations and variations of this are possible – my choice here has been to model a simple user management system with EJB 3 components… in addition, we get some help from a custom Java 5 Annotation, and an EJB Interceptor – this example could just as effectively be implemented with a Spring-based framework as well (probably better, as the EJB 3 Interception functionality is pretty weak – this effort was just as much about proving that EJB Interceptors could be useful as it was about proving the pattern itself :) )…

First off, we have the CRUD Component – I take no credit for this, it is purely from an example by Adam Bien:


public interface GenericCrudService {
public Object create(Object t);
public Object find(Object id,Class type);
public void delete(Object t);
public Object update(Object t);
public Collection findByNamedQuery(String queryName);
public Collection findByNamedQuery(String queryName,int resultLimit);
}


And the implementation:


@Stateless
@Local(GenericCrudService.class)
@Interceptors(RepositoryChecker.class)
public class GenericCrudServiceBean implements GenericCrudService {

@PersistenceContext
private EntityManager em;

public Object create(Object t) {
this.em.persist(t);
return t;
}

@SuppressWarnings("unchecked")
public Object find(Object id, Class type) {
return (Object) this.em.find(type, id);
}

public void delete(Object t) {
t = this.em.merge(t);
this.em.remove(t);
}

public Object update(Object t) {
return this.em.merge(t);
}

public Collection findByNamedQuery(String queryName) {
return this.em.createNamedQuery(queryName).getResultList();
}

public Collection findByNamedQuery(String queryName, int resultLimit) {
return this.em.createNamedQuery(queryName).setMaxResults(resultLimit).getResultList();
}
}



Next, we need a way to identify that a class is a Repository – this may be done in any number of ways, including a properties file that lists each Repository class, a specific class naming pattern (i.e. – MyFavoriteRepository.class), but my favorite is to use a custom Annotation – this particular one has no ‘data’ attached to it, and could potentially be considered a Marker Annotation (thanks again, Adam)… at any rate, any class annotated with @Repository will be able to access the CRUD Component either directly or indirectly (It also serves as a self-documenting annotation, which is another great benefit):



@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Repository {

}


Finally, we need our EJB 3 Interceptor – as you saw above, the GenericCrudServiceBean listed the ‘RepositoryChecker’ Interceptor… the implementation, listed below, will be executed ‘around’ all method calls against the business interface of the GenericCrudServiceBean – it will inspect the StackTrace on the current thread, and use reflection to try and find any class that is annotated with @Repository… as soon as it finds one, it will allow processing to continue – if it does not find one, it will throw an IllegalStateException, indicating the problem for the developer:



public class RepositoryChecker {

public RepositoryChecker() {
}

@AroundInvoke
public Object verifyRepositoryInStack(InvocationContext ctx) throws Exception {

List<StackTraceElement> trace = Arrays.asList(Thread.currentThread().getStackTrace());

boolean foundRepository = false;

for(StackTraceElement element: trace) {
Class currentClass = Class.forName(element.getClassName());

Repository rep = (Repository)currentClass.getAnnotation(Repository.class);
if(rep != null) {
foundRepository = true;
break;
}
}

if(foundRepository)
return ctx.proceed();
else
throw new IllegalStateException("The target class "+ctx.getTarget().getClass().getName()+" must be called by a class marked with @Repository");
}
}



As I said, there are many ways that this could be implemented – I experimented with the idea of using another Interceptor that would place a variable into the InvocationContext when executing around a class marked with @Repository, and simply looking for the existence of that variable in the RepositoryChecker class, but decided against it, as I would need to either explicitly add the new Interceptor on each Repository class, or add it to all EJB 3 components (I could use it instead of @Repository, but I like the self-documenting nature of the annotation)… This alternative implementation would be simpler to build with Spring, as you could use a pointcut to specifically intercept calls on classes with the @Repository annotation…

As for using reflection for this solution – it may become a concern from a performance point of view, but I’m not inclined to worry about it unless there is a real problem… we’re not likely to be spending enormous amounts of time here, and if we are seeing a problem, then we can simply turn off the Interceptor in our staging and production environments, but leave it on for development (or integration, or whatever you call it) – we still get all of the benefits of the pattern (assuming that you actually use the development environment :) ), and most importantly, any developers that break the layering rule will hit it on their own machines, which will make them think twice about what they’re trying to do – ultimately, this is where the most value comes from when using this pattern, as it will help your team to better understand the patterns and policies that are in place on the project…

M

Err... Whaaaaaahhh?

Leave it to Sun to pull a WTF on what may be the most important release for Java on the Desktop in the last decade -- after finally announcing that we're going to get a streamlined, fast, easy to install JRE to compete with Flash and the like, they go an give it possibly the worst product name ever (does anyone remember Bob?) -- "Java SE 6 Update N"... My God, what are they thinking?

M

Friday, September 28, 2007

Woo hoo!

Can you smell that smell? That's the smell of a nice, smooth, clean sheet of ice down at your local rink... that's right, it's hockey season, baby, the best time of the year, and the Rangers are looking to make a run for the Cup (they also apparently sold out the entire season in less than an hour... as the great John Buccigross would say, "Holy Shnikies!")... My fantasy draft is tonight, and things start up next week, which means I'll have a reason to watch TV again (that is, if Time Warner still carries Versus -- I haven't checked since June... the NHL desperately needs to get back onto ESPN!)

I hope to take my son to several games of our local minor league team this year -- he's old enough now to at least sit through most of the game, and perhaps to learn some of the subtleties of the crosscheck and the one-timer (I'm holding out next year for the left wing lock)... well, he seems to think it's cool when someone gets checked into the glass, any way :)

So even if you hate hockey, sports, or whatever, at least go down to the rink to take in that smell... I swear, there's nothing like the smell of the ice!

M

Tuesday, September 25, 2007

Can EJB's be used as more than facades?

In the 'good old days' of EJB 2.x, we were trained to design systems such that the 'facade' was created with EJB Session Beans (usually stateless), while everything behind it could be regular Java classes... there were exceptions, of course, as it may have been necessary to access an occasional EJB from behind the facade if it was located remotely, it had different transactional requirements, or if we were simply dealing with a third party component, but for the most part, this is the mantra that we followed... at some point, Spring came along and made us realize that we didn't really need the heavy-weight EJB's at all, so we threw them out all together... and there was much rejoicing...

Now we have EJB 3, which improves on the old spec in pretty much every way... While I won't suggest that EJB 3 will be usurping Spring usage anytime soon, there are certainly places where EJB's are now at least as good a design choice, if not better... The problem is, we lose the nice Dependency Injection that Spring gives us in these cases...

But hold on -- take a step back and look at your design... if you're designing your app with the old Session Facade in mind, the previous statement is certainly true -- you can't use DI to assemble your domain objects beyond the outer layer -- but I think I can make a case for bringing EJB's back into the heart of your application...

Let's look at reason number one for the original Session Facade -- creating a Session Bean used to be tedious, and it caused us to alter the way we program (ok, reasons 1 and 2, I guess)... but this isn't true anymore -- it's no longer tedious to create a Session Bean -- you just add '@Stateless' to your class... it's also no longer necessary to alter the way we program, at least in many cases -- we don't have to work with Service Locators or Business Delegates, we don't have to manually look anything up in JNDI -- all we have to do is add '@EJB' or '@Resource' to our member fields...

So by allowing any and/or all of our domain objects to be EJB's, we gain the Dependency Injection benefits of acquiring other resources as well... for example, if your Repository or DAO is created as an EJB, you can inject your EntityManager into it quite naturally...

Of course, it's not a perfect scenario... there's some overhead involved in an EJB method call -- security and transaction management, for example -- that could potentially cause your app to be slowed down a bit... personally, I'm not convinced that the slight performance decrease would outweigh the benefits you get from the very natural DI system, but that's purely my opinion... If anyone has any hard data on the kind of performance profile you'd be looking at, I'd be interested in seeing it... additionally, I believe it would be possible for a container to intelligently optimize the calls out in many cases -- I'm not sure how much of this is technically allowed by the spec, but it should be extremely quick to check for an existing, open transaction, for example...

As an aside, the recent Web Beans sneak previews from Gavin lead me to believe that we will be able to get the benefits that I describe above without the drawbacks -- of course, Web Beans may end up signaling a return to the Session Facade for transaction management, while our Domain objects are assembled with the Seam-and-Guice-like Dependency Injection, but hey, it's always good to question what we 'know' occasionally, right?

So is it time to throw away our prejudices against EJB's? I think for a lot of us, it's at least time to reevaluate them...

M

Monday, September 24, 2007

Web Beans Sneak Preview

In case you didn't notice, Gavin King is offering a sneak preview of the Web Beans spec (JSR 299) so far in part 1, part 2, part 3 and part 4... It's been a whole day since his last post, so it appears like now is a good time to put out some thoughts... These are in no particular, but will hopefully serve to continue the conversation to make the eventual spec as useful as possible...
  • Web Beans is not just about the web, as many people have already commented (including Gavin)... while I don't necessarily need it to be brought to JSE, I believe a name change is in order...
  • If Web Beans becomes a generic Dependency Injection mechanism, then we would be left with at least three distinct DI systems in JEE -- the Web Beans DI, the @EJB/@Resource DI from JEE 5, and the Managed Bean mechanism from JSF... something will need to be done to address this (please don't say 'Unified DI', a la 'Unified EL' :) )...
  • The @In annotation clearly comes from Seam, but there might be something more appropriate here -- in Seam, there is also an @Out annotation, representing 'outjection'... So far, Gavin hasn't given us a hint of whether this will be around in Web Beans, but if not, then I think @In should become something like @Inject, @Bean, @Component, etc
  • The Guice influence appears to have replaced the String-based naming in Seam (i.e. -- @Name("myBean") ) with annotations (@MyBean)... while this requires a little more code, it seems to be a good call -- it should help prevent things like typo's in the Strings causing NullPointerExceptions at Runtime...
  • Very flexible -- follows the JEE5 pattern of defining a default configuration with annotations, but allowing it to be overridden or changed with an XML configuration... alternately, the XML configuration could be used as a central configuration file, as in Spring...
  • The various Component Types could be hugely useful for having multiple configurations for a single application, but I would like to see more ways of defining your components -- for example, I like to be able to keep my system configurations in the app server itself, so when I deploy an EAR from test to staging to production, I can simply copy an EAR that has passed QA -- if I have to change the web-beans.xml file, I can't do this (unless there is perhaps a default that you could configure in your server)
  • I love the scopes, but Gavin mentions that the @ConversionScoped will be available from JSF managed beans, while request, session and application will be available from Servlets -- what about JSF makes it the only thing that is appropriate for the conversation scope? Any reason it couldn't be available to Servlets-based frameworks like Struts, etc.?
  • Could we reduce some of the annotation chatter with something like @In (scope=ConversationScoped, new=true)? Hmm... actually that ends up with more chatter -- perhaps not :)
That's enough for now... So far all I can say is "Great work guys!"... oh, and keep the previews coming!

M

Saturday, September 22, 2007

Did Guice beat Sprint to the punch?

There's been a lot of talk over the past few years that perhaps Interface 21 should push to formally make the Spring Framework a part of the JEE specs -- it seemed like it might be possible with Rod Johnson officially declaring his support for JEE 6... well it looks like "Crazy" Bob Lee and the team behind Guice may have found a back door to get themselves into the party first -- according to a new series of articles about the upcoming Web Beans, the new spec is actually influenced by a combination of Seam and Guice, rather than just Seam as previous reports had speculated...

This is not to say that Guice and Spring cover the same ground -- Guice is strictly a product that supports dependency injection, while Spring does that and much more, but I find these articles interesting in that Google has apparently taken the JBoss approach to supporting the JCP -- that is, create an independent product to fill a whole in the JEE specs, and then use the JCP to make that product into a spec itself (take a look at the JPA for a previous example)...

I personally think it's a very smart approach -- while it will perhaps create an opening for competitors to get into the market (more applicable when considering Hibernate and Seam than with Guice, admittedly), it opens up a clear opportunity to provide the first spec-compliant implementation (thus getting early adopters), and gives them a great opportunity to build and enhance their product while the competition is catching up (keeping the early adopters :) )...

We'll see where this goes, but so far it looks like an interesting spec -- I see some potential for overlap between some other specs, but that may not be a bad thing...

M

Friday, August 10, 2007

More on rethinking JEE 5 patterns

Adam Bien often discusses the rethinking of JEE 5 patterns and best practices in his blog, and his latest entry discusses a replacement for the Value List Handler pattern that was prevalent in the J2EE 1.4 and earlier worlds called the Paginator. While I can't say I love the name, the implementation is interesting -- it's really not much different than the old VLH pattern, except that it returns detached JPA Entities instead of Value Objects (hence the reason for the rename)...

What is interesting is that he has implemented the Iterator interface for this implementation, and each call to 'next()' returns a full page of JPA Entities... the code is really quite simple, and I'm sure it could benefit from further use of generics to make this a reusable Stateful Session Bean, but the fact that he is implementing an interface that every Java developer knows and uses pretty much every day (well, before JSE 5 came around, anyway), can only help people realize that perhaps now we can move closer to a real object oriented design... That is definitely a Good Thing... I urge people to take a look at the code in his Subversion repository (and some of the others in there are worth a look, too!)

M

Tuesday, July 17, 2007

The Smoke

Ok, so it’s time to explain the ‘Smoke’ part of the title of this blog – Smoke and Ice… One of my favorite hobbies over the last year or so has been to cook up some fine Southern Barbecue – well, Southernish, I suppose, since I live in New York… I’ll tell you what, you can’t beat the smell of a nice pork butt on the grill, smoking all day long with a nice, spicy rub on it during a summer’s day (or winter… whatever)… from time to time, I’ll be throwing some recipe’s that I use up here, since it’s always best to share barbecue with 30 or 40 of your best friends (and a lot of the time, you’ll still end up with leftovers!)

So let’s start with the basics – I use my standard 22 1/2” Weber Grill… at around $80, you can’t beat it when compared to the many smokers you can get for several hundred, or thousand dollars… Sure, I could cook more with a proper smoker, and I’ll bet it could be done a little better too, since the food isn’t as close to the heat source, but hell, I’m on a budget here… With the Weber grill, I can also fire up the coals to a raging 500-600 degrees, and grill a proper steak as well, so it’s versatile…Oh yeah, and the fuel is charcoal… no gas here – gas grills tend to run too hot, and I just have the feeling that I’d be emptying propane tanks every time I light them up…

As you can probably tell, when I talk about barbecuing, I am not talking about anything to do with ground beef, or fancy cuts of meat… While I love a good burger as much as the next guy, grilling a few burgers does not make a barbecue… instead, barbecuing is the process of cooking over low heat – usually around 225-250 degrees – for extended periods of time, usually throwing some wood right on the coals to produce a fragrant smoke that works it’s way into the meat… additionally, the meat involved is usually tough, with a lot of connective tissue – these meats would be barely edible when cooked on a hot grill, but when allowed to cook slowly, the fat and connective tissue dissolve to make the most tender, lip smacking meal you’ve ever tasted!

My personal favorite right now is South Carolina-style pulled pork, which starts with a 12-15 lb pork shoulder (which, oddly enough, comes from end of a pig opposite the shoulder), takes about 16-18 hours to properly cook, and shreds after cooking like it was butter… I usually buy these suckers two at a time at a wholesale club for about $25, so it ends up being around a dollar/pound, and will literally feed me for a month! (I made up a pair of these this spring for a party with about 30 people, and we not only fed everyone, but had enough for a week and a half of leftovers for myself )… I’m going to fire one of these babies up early next month – I’ll put up a bit of commentary on it when the time comes…

I also do a lot of baby-back ribs and beer-can chicken as well, mainly because they don’t take quite as long, so they don’t take as much care and prep-work (the chicken comes in at about an hour and a half, so it’s something I can start up at 4:00 on a Saturday afternoon)… I’ve tried my hand at brisket once, and while it was a bit tough, the flavor was out of this world, so I will be doing one of those again at some point – I stopped at a barbecue joint the other day and ordered sliced brisket (you know, for research), and surprisingly, it was not at flavorful as mine, and it was nearly as tough… disappointing, but just more motivation to cook it myself

Last but not least – there’s a lot of ‘passive’ time involved in barbecue, and as far as I can tell, there’s only one worthwhile way to pass that time – drink a few beers, listen to some blues and spend time with your family and friends while you’re soaking in that incredible barbecue smell… sound like the perfect way to spend a weekend? Well then get cookin’!


Monday, July 16, 2007

Build Systems

I will admit to being a bit ‘old school’ when it comes to build processes… I will tend to use a tool like Ant that gives me a lot of control over how a project is built, and that is often launched from a command line… I’ve given Maven 2 a chance, and I like a lot of the concepts involved, especially that of Convention over Configuration, but I found that it requires a Herculean effort to do something as simple as building a JEE 5 compliant ear file – this is apparently what happens when the Conventions are based on a previous version of a spec you’re using (to be fair to the Maven 2 project, I found that my biggest frustration was with the documentation – my issues may certainly have been user error, and may be solved with a little better documentation, but my feeling is that it’s simply not there yet)

I’ve also worked a lot with the build processes inherent to Eclipse and NetBeans, but I have not used these for any projects that I collaborate with others on – I think this is mainly because I would prefer not to restrict people to just use my favorite IDE (which most people don’t seem to like – more on that later)…

I have worked most often in a system that uses a bit of both – the best setup for me seems to be one in which the primary build is a series of Ant scripts (Maven, or something else would fit just fine here), while developers are able to work in whatever IDE they like – if that IDE provides its’ own compilation system, then great, but the code that is compiled here doesn’t actually matter for anything, because the runtime system uses the class files created from the Ant scripts…

In some ways, this feels more like a compromise system to me than anything else, and it’s often difficult to get less experienced developers to realize that if their IDE is showing that they have an error, but the Ant script still builds, then it’s not a big deal (not to mention that a situation like that just seems a bit smelly anyway)…

Do other projects work in this way, or is there a ‘better’ way, in which both the IDE and the build scripts use the same class folders? I’m willing to bet that this is doable, but I haven’t had the opportunity (or patience ) to pursue it yet…

Wednesday, July 11, 2007

Rethinking Best Practices

Ah, J2EE best practices -- the community's way of figuring out how to work with flawed technologies... You know, the Session Facade, Data Transfer Objects, etc. -- they are ingrained in so many developers' brains to the point of being second nature... It feels almost instinctual to design your system with them -- putting your data over here in these classes, putting your logic over there in those classes...

Problem is, now that JEE 5 is becoming more common, those best practices are all wrong... ok, in most cases they won't necessarily cause any harm (at least not of the magnitude of not following best practices about 5 years ago), but there are now better ways of doing things -- we just need to learn what they are...

I'll touch on a number of these in future posts, but I find that the area I have a lot of trouble with is getting rid of my habit to separate my data from my logic... the Session Bean/Entity Bean separation, in my opinion, is one of the more damaging patterns that was literally forced upon developers who went down the EJB path in the early days, and it's a pattern that I'm not convinced is completely fixed yet... more on that in a later post...

Personally, my 'toy' projects are partially intended to get me thinking away from this -- when it comes down to it, it's all about trying to relearn those object oriented design principals, incorporate some newer techniques like Domain Driven Design, and just experiment in whatever way suits my fancy...

The first thing I do is put together my initial design in some form -- either code, UML, a drawing, whatever... then I do it again, and look for specific flaws, like classes with only data and no behavior and vice-versa... of course, these scenarios aren't always wrong, or even bad, but each time I go through this retrospective, I get a little better at identifying these issues to start with...

Do you have similar experiences? Spill the beans, let us know!

JEE and Spring

How are people using JEE 5 and Spring these days? There's a lot of overlap in the technologies, obviously, and there are reasons to use both, but I'm interested in those using them collaboratively...

I've seen some articles about how one can integrate the two by accessing a Spring ApplicationContext from within an EJB 3 Session Bean, but none of them seem to address the fact that the two have different life cycles -- using dependency injection within a Session Bean's PostConstruct method could cause some unexpected problems if you're using Spring's prototype scoping... there's no guarantee that the PostConstruct will be called for each invokation, but only when the bean is originally created...

Has anyone out there dealt with this? Would it be possible to create an 'ejb' scope with Spring's new customizable scopings?

Howdy!

Howdy, y'all!

Yes, I know, it's another 'First Post' message... yeah, I'll get on with it... This blog will be a place for me to put my thoughts, whether they be about programming (my profession), barbecue (the 'Smoke' from the blog's title), hockey (read the title again), family, movies, books, whatever... More than likely, I'll end up figuring all of that out as we go...

Ok, ok, I'm getting on with it... you'll have to wait for the next post for anything else...