spacer

 

Monday, December 08, 2008

I Hate Casting!

I don't mean to sound like Grumpy Smurf but did I tell you I hate casting? Thanks to the new JDK 1.5 templating I can finally eliminate them!

Eliminate Them! (A quote from Star Trek Insurrection)

An Enterprise Java Bean Example
// Old
private UserSessionHome getUserSessionHome() throws Exception {
  return (UserSessionHome) initialContext.lookup("ejb/UserSession");
}

private AccountHome getAccountHome() throws Exception {
  return (AccountHome) initialContext.lookup("ejb/Account");
}


// New
private UserSessionHome getUserSessionHome() throws Exception {
  return getHome("ejb/UserSession");
}

private AccountHome getAccountHome() throws Exception {
  return getHome("ejb/Account");
}

private <T> T getHome(String jndiName) throws Exception {
  return (T) initialContext.lookup(jndiName);
}

Usage Example:

UserSession userSession = getUserSessionHome().create();
userSession.createUser(userInfo);
A Spring DAO example
@SuppressWarnings("unchecked")
public <T> T get(Class entityClass, Serializable id) {
  return (T) super.getHibernateTemplate().get(entityClass, id);
}

In your DAO Implementation Class:

// OLD (with Casting)
public User getUser(String username) {
  return (User) super.getHibernateTemplate().get(User.class, username);
}

// New
public User getUser(String username) {
  return get(User.class, username);
}

Hey, wouldn't it be nice if the Spring developers provide an IBatis SqlMapTemplate and HibernateTemplate specifically for JDK5 to eliminate casting. My 2 cents...

No comments:

Popular Posts

Featured Post

Encrypting Properties File Values with Jasypt

Encrypting Properties File Values with Jasypt What's the fuzz all about? Property files are text resources in your standard web applic...