Immutable data model objects in the MVC view

Posted by: on Aug 25, 2005 | No Comments

I’ve long been uncomfortable with putting standard beans into the model used to render a view in a web application. It’s fine when I know it’s me editing the view templates (typically WebMacro), however in other situations – especially if there might be concurrency issues – you shouldn’t really be putting mutable objects into the view model just in case somebody decides to get clever and change some properties of your beans.

After playing with several solutions over the last few years, I came up with a quick and simple solution the other day. Using  CGLIB and a custom interceptor, it is relatively trivial to create dynamic "proxy" classes of any data bean that cache all the readable property values and throw an exception if any setter or other method is called.

The beauty of this is that the proxy class does not have to implement an interface – which is usually a good idea but not always practical in legacy code – and it does not need to retain a reference to the original mutable bean. Java 1.3+ dynamic proxies will only proxy interfaces, but CGLIB allows you to proxy concrete classes.

Leave a Reply