Dan reveals all the secrets of Naked Objects.
Naked Objects is a Java framework that lets us build enterprise applications from the domain model out. Dan makes the business case for Naked Objects and walks us through what it’s like to go Naked.
If, like me, you spend your working time developing enterprise applications then I’m sure you’ve encountered the layered architecture: presentation, application, domain, and infrastructure (or persistence). Separating out these concerns gives us modular, maintainable applications.
Now of these layers, the bit that matters most to the business is the domain layer; after all, it’s the domain model within that distinguishes our business from our competitors. Sure, the app has to look nice, and has to handle transactions and workflow and stuff, and of course the data needs persisting somewhere, and we may need to integrate with other systems in the enterprise … but these are all supporting functions, not ends in themselves.
No. What the business stakeholders want when they pay for an enterprise app is something that reflects their way of doing (or wanting to do) business. It should automate the mundane stuff, and also handle any complex rules, while providing enough flexibility to let the app’s end users exercise their discretion for edge cases. That’s quite a high bar.
Building an app the traditional way requires us to implement all of those layers, but of course that means it’ll take us that much longer to implement a user story to demo to the business. Slower velocity means it’s gonna take us longer to discover the critical insights into the domain, as well as more to rework if we discover we were going down the wrong track.
Worse still, it’s easy to misplace logic that should be in the domain model into those lovingly hand-crafted presentation and application layers. Not only have we broken the modularity we were aiming for, that demo to the business isn’t really demonstrating the domain concepts, because they’ve been distorted or obscured by the layers above.
What to do?
The Hexagonal Architecture
The trouble with the layered architecture is that it makes us think of one layer stacked on top of another. A few years back Alistair Cockburn came up with an alternative view, which he originally called ports and adapters, but is more often called the hexagonal architecture .
The hexagon emphasizes the fact that there are multiple entry points—or ports—both into the system and out of it. The presentation layer adapters use the primary ports, while the secondary ports allow the system to interact with the adapters in the infrastructure layer. So for example an HTML viewer adapts the application for use over the web.
With this approach, we can start focusing on the domain model without getting distracted by the other layers. We can use FitNesse  or other agile acceptance-testing tools to exercise the system from the application layer down, without getting bogged down by widgets, data transfer objects, and all that other stuff that comes with the presentation layer. And we can switch out the RDBMS, with all the hassle of dealing with database schemas and managing data, for a simpler implementation, say an in-memory object store.
So where does that leave us?
Well—if you’re on the same page as me—it leaves us looking for something to take care of all that stuff for us and let us focus on the domain model. Obviously that would need to be some sort of framework, but we wouldn’t want it to be invasive, because we wouldn’t want our code to have dependencies on such a framework. In fact, it would need to be flexible enough to play with any of our own runtime GUI frameworks or infrastructure. Or, if we hadn’t gotten around to writing our own infrastructure, it should just be a full stack framework to use out of the box. Now wouldn’t that be cool?
Focusing on Just the Bit That Matters
Naked Objects is an open source Java framework  (commercial on .NET ) that lets us build enterprise applications from the domain model out. With Naked Objects we write our domain model as plain old Java objects (pojos). What the framework then does—at runtime—is to create an object-oriented user interface to allow our end users to interact with those domain objects.
You can think of it analogously to object-relational mappings (ORMs) such as Hibernate . Hibernate builds a persistence metamodel from your domain objects, and uses this metamodel to persist your pojos into an RDBMS. Naked Objects likewise builds a presentation metamodel, and uses this to render your objects in the presentation layer, either in a client/server Swing-like UI (we call it the drag-n-drop viewer), or an HTML web viewer.
This metamodel is built up using rules similar to Hibernate, too. Naked Objects uses getters/setters to identify a class’s properties or, if they return java.util.Collection, then collections. Any public methods “left over” are actions allowing arbitrary business operations to be performed on the domain objects. These are exposed using menu items or (on the web) links or forms.
For example, here’s the drag-n-drop viewer running a simple expenses application:
Each window within the frame corresponds to an instance of a domain object, and the whole thing is generated automatically at runtime. So, the Claim class has a description property defined like so:
Similarly, the Approver property is:
There are similar properties for Date, Status, and Claimant. Meanwhile, the Items collection is:
So far so good, but there are lots of other frameworks out there that can also automatically let us build CRUD-style applications out of “know-what” responsibilities. However, Naked Objects goes further by also exposing actions that encapsulate “know-how-to” responsibilities. In the screenshot, you can see there’s a submit action on the menu item for the Claim object. Here’s the code that gives rise to that:
This is a really simple action, but in principal it could be arbitrarily complex. There’s a similar block of code for the add item action.
I mentioned that Naked Objects provides an HTML viewer, too. Here it is running the same application:
Obviously it looks somewhat different, because HTML has a different interaction idiom from desktop apps. But we’re still looking at a Claim object, and we can see the same properties, collections, and actions.
Meanwhile, here’s the entire codebase for this app:
There are no controllers, no Swing forms, no JSPs, no DTOs, nada. This particular app is entirely made up of three main classes (Employee, Claim, and ClaimItem), two simple interfaces (Approver and Claimant, both implemented by Employee) and two repositories that provide access to existing objects (ClaimRepository and EmployeeRepository). For a closer look, you can download this example from Naked Objects’ SourceForge project page.
In the code samples, you might have noticed a number of annotations (such as @Disabled and @MemberOrder). So, yes, I lied; we aren’t quite writing pojos. These are pojos++.
If we write a method in a public API that could be called from possibly untrusted code, then there are two things it should do. First, it should ensure that the object is in a valid state to be interacted with; in other words, that the class’s invariants are satisfied. Second, it should also check that the arguments passed in are valid before we go ahead and execute the rest of the method.
These business rules are intrinsic to the domain model. The @Disabled annotation just specifies a very simple class invariant: it says that the object cannot be interacted with through the annotated class member at all. Naked Objects interprets this by rendering the property as non-editable (or preventing an object from being added to a collection, or by graying out a menu item for an action).
We can also specify validation rules for arguments. For example, because the submit action’s Approver parameter is not annotated, as @Optional means that it is required. Naked Objects will interpret this rule by graying out the action’s OK button until an approver is supplied.
The metamodel built by Naked Objects doesn’t only rely on declarative semantics. We can also capture business rules imperatively. Looking back at the code you’ll see a disableSubmit() method, returning a String. Any non-null value is interpreted as the reason why the corresponding member (the submit action in this case) is disabled. And again, Naked Objects interprets this by disabling the class member in the GUI. In this case, the user won’t be allowed to submit a claim once it has been submitted. Of course, there are also some semantics that are entirely for presentation concerns.
See It? Use It? Do It?
Earlier on I drew an analogy with Hibernate. Once upon a time we used to use Hibernate’s .hbm.xml files to describe the persistence metamodel, and some people still do. But the alternative approach—and the JEE standard—is to use JPA annotations, with the metamodel built out from there. For example, @Entity (in the javax.jpa package) indicates that a class is persistent, @Id specifies the primary key, and @ManyToOne identifies a foreign key relationship. Taken together, these annotations extend the semantics of the domain classes, and in so doing allow the JPA provider (Hibernate) to take care of the persistence for us.
In the same way, then, annotations such as @MemberOrder extend the semantics of the domain model to capture presentation concerns. @MemberOrder tells Naked Objects the order to display fields in the UI; it’s basically a rendering hint. Some others are @Named (to override the name inferred from the class member), and @DescribedAs (a longer description, for example represented as a tooltip).
Let’s go back to those business rules. Class invariants and validation are two types of rules that are intrinsic to the domain, each of which Naked Objects represents in the GUI by disabling links, etc. But if we think about exposing that method as an action in the UI, there is another check we should make: whether the class member (action, property, or collection) is visible.
So Naked Objects basically asks three questions: is the class member visible (can you see it?); if so, is it enabled (can you use it?); and if so, are the proposed values/arguments to change the state OK (can you do it?). The first two of these enforce class invariants, the last is validation in the traditional sense. And each of these rules can be implemented declaratively using annotations or imperatively using supporting methods.
For example, suppose I have a security management system and the security administrator sets up a new account. We might allow her to specify an initial password before the account is persisted, but we wouldn’t want her to see that password after it has been persisted. Here’s how we do that:
Here we use the @Hidden annotation to selectively tell Naked Objects when the property should be visible, based on the persistence of the object. Which Naked Objects can do because it also is a full stack and so tracks the persistence of all domain objects.
Thus far we’ve only talked about how Naked Objects removes the need for us to write a custom presentation layer. But the Naked Objects metamodel in effect also removes the need for a custom application layer. This “see it? use it? do it?” mnemonic effectively summarizes the protocol between the application layer and the domain layer. Naked Objects not only implements a generic object-oriented UI, it implements a generic application layer.
Fixing It Up
So far we’ve only focused on the layers in front of the domain layer, but if we want an application to demonstrate to the business, then we also need to deal with the persistence layer.
Naked Objects is compatible with Hibernate and provides an object store implementation that uses Hibernate under the covers . But while we’re exploring the domain, we want something that we can turn around somewhat faster. For this we use an in-memory object store (indeed, this is the default when running Naked Objects in “exploration” mode).
Of course, any objects stored in an in-memory object store will disappear when we close down the application, so we need to populate the object store on startup. For this we use fixtures:
The install() method is called by the framework during initialization, and then populates the object store as required. For larger applications, we usually arrange fixture classes into a hierarchy using the composite pattern. This allows us to easily compose different fixture sets for different scenarios we want to demonstrate to the business, running the app using a command-line flag:
A common approach is to separate static (reference, standing) data from transactional data. When we get to integrating with a production RDBMS object store, we can use the reference data fixtures to populate the database.
Which is nice. But suppose we want to move out of exploration and into something a little more formal, with user stories, acceptance test criteria, all that good stuff. Indeed, our fixture scenarios ought really to be developed with respect to those user stories. How do we go about testing our domain model?
Fit for Purpose
Here’s how. We use FitNesse, an agile acceptance testing tool. After all, FitNesse is just another viewer in the presentation layer.
In FitNesse we write our acceptance test scenario using a wiki. FitNesse then calls out to adapter code which in turn exercises our application. In traditional applications this adapter code must be written by the developer, but with Naked Objects we have nothing to write. Instead, we get generic adapters that—using the metamodel—allow us to interact and inspect domain objects for free .
For example, suppose we wanted to test the logic that a claim can’t be submitted again once it has been submitted. Here it is working in the GUI:
And our FitNesse acceptance test script lets the business user verify this same functionality:
If the business user wants, they can run the application alongside the test script to check that it performs as advertised. But the point of FitNesse is that both the representation of the tests and the results are friendly to a non-technical domain expert, so there’s generally no need.
How Do We Measure Up?
Let’s go back to that “wishlist” again. That framework shouldn’t be invasive? Yup, we use pojos plus some annotations. It should also be flexible? Well, yes, actually Naked Objects does provide an API to allow you to replace its programming model conventions with any other conventions as you want. It should also be usable out of the box? Yup, Naked Objects does that, too, providing a Maven archetype to get you started. Oh, and it’s about as extreme an example of the DRY principle as you might hope to meet.
Now you’ve see what Naked Objects can do. But what if you want a half-way house? Let Naked Objects do its stuff early on, but skin the app using custom presentation layer later—implemented in Wicket , say—once the domain concepts are firming up. That’s even, dare I say, the kind of thing you could outsource; after all, enterprise application developers are notoriously bad at putting together good-looking GUIs.
All of this talk of domain objects might also have put you in mind of Eric Evans’ domain-driven design , in which case, go to the top of the class! Naked Objects is a natural bedfellow for domain-driven design, and uses DDD concepts such as entities, values, repositories, and factories. Its use of the hexagonal architecture also makes it great for tackling more strategic DDD ideas such as bounded contexts, domain services, and infrastructure services.
As I said before, Naked Objects is open source on Java, under the Apache License v2. It provides Maven archetypes to get you started, and it has a bunch of sister projects that extend its capabilities into FitNesse and Hibernate (as discussed) as well as REST. Oh, and there’s a book about it ;-) So, cast aside your inhibitions and get naked. Your business users are gonna love you for it.
Dan Haywood is a freelance consultant, agile coach, and developer based in the UK. He’s been involved with Naked Objects since 2002, and is an advisor to the Irish Government for a 600+ user system administering pensions and other state benefits, built with Naked Objects. He is also the author of Domain Driven Design using Naked Objects, published this month at Pragmatic Bookshelf.