Naked Objects 3

Java Development News:

Naked Objects 3

By Richard Pawson

01 Oct 2007 | TheServerSide.com

We are pleased to announce, today, the release of Naked Objects 3.0. For those not familiar with earlier versions, Naked Objects is an open-source Java-based framework that takes a POJO domain object model and turns it into a complete, executable application. It auto-creates a user interface that is a direct reflection of the domain model, offering the option of either a rich-client interface or a pure HTML interface as shown below (you can view both on our online demonstration application); and it auto-creates a persistence layer using Hibernate.

How does Naked Objects differ from other frameworks that can auto-generate a user-interface and/or persistence layer from POJOs, such as Ruby on Rails, or Grails? The answer is that most such frameworks employ the MVC pattern, with the result that much of the business behavior ends up in the Controllers that sit on top of the domain entities. By contrast Naked Objects neither requires, nor permits, the specification of Controllers: all business behavior must be encapsulated as methods on the domain entities. This makes Naked Objects one of the most 'opinionated' frameworks in existence!

The advantage is that Naked Objects both requires and facilitates the specification of very pure domain object models - and this results both in higher agility (ease with which future changes in requirements can be accommodated) and also in far greater levels of re-use. At the DSFA in Ireland, where we have implemented a set of large scale mission-critical applications using Naked Objects (2.0), we aimed for 90% re-use of the business code between applications; for one significant new application we achieved 98% (meaning that we replaced an application that had 50,000+ lines of bespoke business code with one that contained <1000 lines). The DSFA's now has more than 700 officers using its Naked Objects applications on a daily basis, many of them continuously.

This illustrates another important distinction. Ruby on Rails and similar frameworks are explicitly web development frameworks: they can be used to design web-based applications either for internal use within an organisation or for public access. Applications delivered using Naked Objects are suitable for internal use only: not for public access. We have never claimed that the resulting user interface is 'intuitive' - actually, research clearly shows that there is no such thing as an intuitive user interface, only a familiar one - there is a definite learning curve involved. But our aim has always been to deliver user interfaces that treat users 'as problem-solvers not merely process-followers'. Indeed this was one of the features that appealed strongly to the DSFA and has been demonstrably successful in action.

That said, there's nothing to stop you from developing and delivering an application for internal use on Naked Objects, and then accessing the same POJO domain objects via a more conventional scripted user interface for a different user community. In fact, you could use Naked Objects just as a prototyping tool for developing your domain object model, with the intent that the resulting domain model will then be deployed on a more conventional architecture.

Certainly, Naked Objects is a much more effective way to involve users and business stakeholders in the domain modeling session that trying to engage them with UML diagrams! Ideas can be translated very quickly into functional prototypes, because all you write are the domain objects themselves. More importantly, because the UI is a direct reflection of the domain objects, users and business stakeholders can see the significance of choices in how the domain is modelled: if there's something you can't do in the Naked Objects prototype, that means there's something missing or wrong with the domain model. This is in marked contrast to most approaches, where deficiencies in the domain modeling are, literally, masked by views and controllers.

We are often asked, “But how do you create a view that includes attributes from more than one object?” We don't. We suggest that that practice just masks deficiencies in the model. We've built large and very complex applications using Naked Objects and we've never found this to be a constraint.

The other advantage in prototyping with Naked Objects is that it prevents the discussion getting bogged down in the detail of the user interface. This takes a little adjustment since most software development organisations have more or less trained their customers to focus on the detail of the user interface rather than the, much more important, issue of the domain model - initial reactions of the kind 'Wad'ya mean I can't have the third line down in 24pt Garamond!' are not uncommon. But very quickly that drops off and all that the participants concentrate on are the objects and their capabilities. At the DSFA they no longer talk about their applications as having a user interface, because they don't perceive that there is one. (It's like riding a motorbike: most riders are not aware of the user interface - the fact that in order negotiate a right-hand bend the first step is to turn the handlebars slightly to the left!)

If you start off prototyping with Naked Objects then we're confident that sooner or later you're going to think about deploying an application that way as well. Most of the work we've been doing over the last 18 months on designing version 3.0 has been in making Naked Objects easier to deploy in an enterprise architecture. Let's look at some of these capabilities.

Java 1.5 programming model

Naked Objects is designed to work with Java 1.5, making use both of generics and of annotations. Consider this code fragment:

@MemberOrder(sequence = "2")
@Optional
@RegEx(validation = "(w+.)*w+@(w+.)+[A-Za-z]+")
public String getEmailAddress() {...}

@Member order tells Naked Objects where the EmailAddress field should be rendered in relation to other fields. @Optional indicates that it is not a mandatory field i.e. the object may be saved without a value here. The final annotation specifies the RegEx for validating the user input. Some programmers react in horror to all three of those: isn't it just forcing logic that 'belongs' in the UI into the domain objects? We argue that all three of those pieces of information are natural properties of the domain object, scattering that information across multiple screens and/or controllers is a bad idea. By placing it where we have the information is picked up and interpreted by any of the different UIs in a form that fits that style of UI.

Injected services

Naked Objects supports the dependency injection pattern as pioneered by the Spring framework. Naked Objects does not depend upon Spring; we tend to use Spring in our deployments to look after dependency injection between components of the overall architecture; but the Naked Objects framework has its own automatic mechanism for injecting dependencies into domain object instances. All you need to do is provide a property (actually just a setter) for the type of service that a domain object needs access to and Naked Objects will inject an instance of that service type whenever the domain object is brought into memory. For example:

private EmailSender emailSender;

protected EmailSender getEmailSender() {
    return this.emailSender;
}

public void setEmailSender(final EmailSender emailSender) {
    this.emailSender = emailSender;
}


public void sendEmail(Customer cust, String message) {
    getEmailSender().sendTextEmail(cust.getEmailAddress(), message);
}

Alternative user interfaces

As stated earlier, Naked Objects includes two alternative user interfaces: a rich-client ('Drag and Drop') UI and a pure HTML UI. Naked Objects 3.0 is also designed to make it easier to write other forms of generic user interface. Over the next few months we expect to see several new user interfaces made available for Naked Objects, including a command line interface, and an Eclipse RCP user interface. AJAX is another obvious direction, and we know that Dave Crane, author of the best-selling ' Ajax in Action' book has been experimenting with Naked Objects.

Hibernate Object Store.

There is an obvious synergy between Naked Objects and Hibernate. Indeed for people who already use Hibernate to derive their persistence layer from a POJO domain model, Naked Objects can be thought of as performing the same function but upwards to the presentation layer. Naked Objects 3.0 includes a sophisticated Hibernate Object Store, which, as well as allowing you to map your domain objects to a database using Hibernate mapping files, can generate the entire schema automatically. Naked Objects also provides an abstract HibernateRepository class that makes it easy to write your repository methods as illustrated in this example (where 'hibernateHelper' is an injected service of a type provided with the Naked Objects application library:

private List<Claim> findAllClaims(final Employee employee,
final ClaimStatus status, final String description) {

  final Criteria criteria =
hibernateHelper.createCriteria(Claim.class);
  if (employee != null) {
    criteria.add(Restrictions.eq("claimant", employee));
  }
  if (status != null) {
    criteria.add(Restrictions.eq("status", status));
  }
  if (description != null) {
    criteria.add(Restrictions.like("description", description,
MatchMode.ANYWHERE));
  }
  if (maxClaimsToRetrieve != null) {
    criteria.setMaxResults(maxClaimsToRetrieve.intValue());
  }
  criteria.addOrder(Order.desc("dateCreated"));

  return hibernateHelper.findByCriteria(criteria, Employee.class);
}

Security model

Visibility of classes, properties and actions can be specified according to a user's role(s). The permissions may be specified and administered via LDAP, a database or flat-files.

Contributed actions

In a Naked Objects application, every object has a menu of associated actions (on the rich client interface this appears as a pop-up menu; on the HTML user interface the menu appears as links from the page representing the object). Any public method on an object, that has not been explicitly hidden by the programmer (e.g. using @Hidden) will appear on the action menu for the object, assuming that the user's role has permission to see that method. With Naked Objects 3.0 there is an additional twist:added to the menu will be any method from any registered service that is visible to that user, and that takes that object type as one of its parameters. For example, the method:

public List<RecordedAction> allRecordedActions(
RecordedActionContext context) {

return recordedActionRepository.allRecordedActions(context);
}

defined on a service will result in the menu-action 'All Recorded Actions' being added to any domain object that implements RecordedActionContext (which need not define any methods). If the user selects that action, it will execute using the domain object they are focused on as the parameter.

This is an extraordinarily powerful programming pattern, though it takes a bit of getting used to. The net effect is somewhat like Aspect-Oriented Programming, though it is not strictly AOP per se.

(We did look at the possibility of making explicit use of AOP within Naked Objects 3.0, but decided that that might narrow its appeal. However, if you are familiar with AspectJ and happy to use it on your project then there are certainly synergies to be gained. (For more on this, see my recent blog.)

License

Finally, in response to pleas from a number of users, especially those in corporate environments, we've switched the license from GPL to Apache.

Conclusion

Naked Objects has always been a controversial idea. MVC is so ingrained as an idea that many developers can't imagine that there are other possible patterns. A few years ago I met Trygve Reenskaug for the first time: the man who invented MVC in 1978. I had good reason to be nervous about his reaction: the context of the meeting was my PhD thesis defense (entitled 'Naked Objects') and Reenskaug had been selected by the university to be the external examiner! His response was both gracious and enlightening: it was not the original intent of MVC that the controllers should become 'use-case controllers' as is now the common implementation; Controllers were meant only to provide a technical capability. And it was his intent, never realized, that it should be possible to create completely generic viewers and controllers such that all you would need to write for an application would be the model objects. Naked Objects is the realization of that vision.

Biography

Richard Pawson has been working in the IT industry for 30 years, joining Commodore in January 1977: the month they launched the world's first assembled personal computer (the Pet). He spent 14 years with Computer Sciences Corporation (CSC), latterly as Vice President and Director of Research. Naked Objects was the culmination of more than 10 years research into agile systems development in general, and object-oriented techniques in particular - culminating in his PhD thesis in 2003. That year he co-founded Naked Objects Group with Robert Matthews, the principal author of the Naked Objects framework. Richard lives in Henley-on-Thames in the UK, in a house that he designed using Christopher Alexander's A Pattern Language.