Pages

Friday, May 25, 2012

Using container objects instead of fields ?

You know the POJOS, the one with getters/setters ?
 public class UserPojo {  
   private Serializable id;  
   private String login;  
   public Serializable getId() {  
     return id;  
   }  
   public void setId(Serializable id) {  
     this.id = id;  
   }  
   public String getLogin() {  
     return login;  
   }  
   public void setLogin(String login) {  
     this.login = login;  
   }  
...
 }  
What now if we need to serialize this to XML or JSON. Instead of using something like Xstream maybe we could do it like this :
 public class UserPojo {  
   private JSONObject jsonObject;  
   public UserPojo() {  
     jsonObject = JSONObjectHelper.newJSONObject();  
   }  
   public Serializable getId() {  
     return (Serializable) JSONObjectHelper.get(jsonObject, "id");  
   }  
   public void setId(Serializable id) {  
     JSONObjectHelper.put(jsonObject,"id",id);  
   }  
 ...  
 }  
We are building the JSON object as setters are called. No need of a reflection api . Although now we are dependent to JSON or XML or whatever... I could think of runtime proxy generation code that would replace the getter/setter code but I really don't like class definitions that hang in memmory. May be some spi stuff and a more general api could be introduced which would let your POJOs store the data in whatever format you choose.
As for me I think this is a good fit to use with MongoDB because know I can convert my POJOs easily  to MongoDB's DBObject:
 (DBObject) JSON.parse(hasJSONObject.getJSONObject().toString());  
and fill up my POJOs with MongoDB data:
 User user = new User();  
 user.setJSONObject(dbobj.toString());   
And again a good fit for JAX-RS  in which case It would convert my POJOs without going through some reflection process.
It would even be better if I could configure my POJOs with an api to store data both within a JSONObject and a MongoDBs DBObject without a compile time dependency.
Looks like a simple way to do things ?

2 comments:

  1. Looks decent.
    Did you ever look at GWT's AutoBean ? (http://code.google.com/p/google-web-toolkit/wiki/AutoBean)
    (I looked at it, but did not use)
    Basically you define interfaces only and a bean factory creates concretes with json support built in. I imagine it might work quite well with your MongoDB objects.

    ReplyDelete
  2. AutoBean api looks good. Though it probably uses some runtime code gen. lib.
    Thanks for the input
    Regards

    ReplyDelete