January 2019

Volume 34 Number 1

[The Working Programmer]

Coding Naked

By Ted Neward | January 2019

Ted NewardReaders who missed the last column may be surprised that I’m not still talking about the MEAN (Mongo, Express, Angular, Node) stack; that’s because I wrapped up the series last time, and now it’s time to turn the attention toward something a little different.

In the MEAN series I systematically deconstructed the entire stack and examined each of its constituent parts in detail. Now I’m going to take a look at a stack (well, technology, singular, really) that’s designed to blend all of its parts into a single, seamless whole, one that’s intended to be used to hide much of the low-level detail work required. In other words, sometimes developers “just want to work with objects,” without having to worry about building out a UI, database or intermediate middleware. In many ways, this is the ultimate expression of what Alan Kay had in mind when he invented objects, back in the days of Smalltalk (which was Kay’s original object-oriented language), and it’s a natural, logical extension of the Domain-Driven Design (DDD) concept (or, perhaps more accurately, the other way around).

Smalltalk, when run, always executes inside a larger environment called a browser. In essence, the browser is a runtime execution environment, IDE and UI host all wrapped into one. (By comparison, an HTML browser is usually just a UI host, although several vendors, including Microsoft, are trying like mad to make the HTML browser into both an IDE and execution environment.) When a developer defines a new class in Smalltalk, the browser knows how to build a generic UI around a given object, and (depending on which vendor’s Smalltalk) knows how to persist that to a relational store or to its own object database. The developer doesn’t need to define “views” or “controllers,” and “models” aren’t anemic data-only classes that essentially just define a database schema. In many respects, this is object-oriented the way it was meant to be: Developers interact with customers, find the objects, define properties on those objects (and the relationships between them), define behaviors on those objects and ship the project. It was for this reason that Kay once said, “I invented the term object-oriented, and I can tell you that C++ was not what I had in mind.” All jokes at the C++ language’s expense aside, his disapproval was with all the thousands of objects that stood between the user and the actual domain object being manipulated. (Well, that and the whole directly manipulating-memory-through-pointers thing, but let’s stay focused here.) Which means I can presume he’d be equally disappointed in C# and Java. (And Node.js, to boot.)

Naturally, developers have sought to recreate this Holy Grail of object programming, and I’m going to examine one of these attempts, which goes by the name of Naked Objects. (No, I’m serious, that’s its name, which derives from the idea that developers should be focusing solely on the business domain and users should be able to work with the objects directly “without additional decoration,” if you will. Or, put another way, users should work with objects in their natural, “naked” state.)

In essence, what’s happening in this approach is equally intri­guing and intimidating: Based on metadata gathered from an object at run time (via Reflection calls, usually), you generate a UI that knows how to display and edit the properties on the object, validate the edits based on additional metadata specified on the object (usually via custom attributes) and, if necessary, reject those changes that don’t meet validation. From there, you query for and store the object to the database (typically through an object/­relational mapping layer), along with any additional objects that might require updates, such as objects linked by ownership or some other relation.

Of course, part of the attraction to using the Naked Objects Framework is all the puns to be made. Ready to shuck it all and dive in?

Getting Naked

Fire up a browser, point it at nakedobjects.org and notice that the Web site is a simple redirect site that lets you choose where to go, depending on which platform holds your interest: There’s a .NET flavor (which will be my focus) and a Java flavor, which also goes by the name Apache Isis. (Again, not kidding—the folks in charge of Isis are thinking about changing the name, but to be fair, they chose the name long before the folks in the Middle East did.)

When redirected to the .NET flavor, you end up on the GitHub project page for the NakedObjects Framework project, which as of this writing is at version 9. The project page has two notable links on the README homepage: One is to the Developer’s Guide, which is a must-have when working with the framework (and a great example of documentation done well), and the other is a .ZIP file containing a template solution to use as a starting point. While the NakedObjects Framework (abbreviated NOF) assemblies are available through NuGet, it’s generally easier to use the .ZIP template to begin your new NOF project, for reasons that will become more apparent later. For now, grab the .ZIP template, explode it into a subdirectory for code, and open up the Solution file in your favorite instance of Visual Studio.

When Visual Studio finishes loading, you’ll notice that the solution is made up of several different projects, five to be exact. For the most part, their names are self-explanatory: Template.Client will be a Web client, Template.Server is the Web server, and Template.DataBase and Template.SeedData represent the layers for talking to the database. (In essence, the last two are pretty straightforward Entity Framework projects, so if you already know EF, you’ve got the persistence part of NOF down, as well.)

The last project in the solution, Template.Model, is where most, if not all, of the developer work will take place. This is the collection of classes that represent the domain model of the project and, therefore, the bulk of the work that a developer will need to do should—and usually will—be done here. Fortunately, the NOF template already has a bit of sample code in it—a Student type, representing one of those creatures who loves to study—so let’s just fire it up and watch it go. Make sure that Template.Server is set as the startup project (which it should be already), punch F5 and relax.

Running Naked

First, Visual Studio will fire up the server component and, owing to the EF default configuration, will take a few moments to build the database out of nothing to start. A few seconds after start, some JSON will appear in the browser window—this is because the Template.Server is actually a RESTful server, which means not only does it operate over HTTP, it serves back JSON that describes the entire collection of options that a user can take advantage of if they want. Notice the JSON consists of what basically look like hyperlinks: “rel” for “relation,” “href” for the URL to use, “type” to describe what’s expected and so on. This is so that developers who don’t want to use the generic UI (which I’ll examine next) can create their own UI that knows how to work from the JSON being handed back.

Let’s look at the UI that NOF builds for you. In a new browser tab, navigate to http://localhost:5001. The result that comes back is … stark. It’s clearly not built to be pretty, and to the unfamiliar eye, it looks like there’s no real starting point. However, remember that REST (as Fielding originally intended it) and Smalltalk had similar aims: a universal UI, so that regardless of the domain, a user would know how to operate it. NOF is essentially building the UI collectively off of a number of static methods of classes, and these will be displayed in the top-level Menu from that homepage. Clicking it reveals three options: “All Students,” “Create New Student” and “Find Student by Name.” Pretty clearly, these are simple CRUD methods (well, C and R, anyway), so let’s see who’s already in the system. Click All Students, and three students (that are fed to EF on startup from the Template.SeedData project) will appear, along with a curious icon in the upper-right of the list returned. Clicking this icon will display the results as a table instead of just a list, but because Students only have a FullName property and nothing else, this won’t seem all that interesting yet.

Selecting a student from that list will occupy the full page. Let’s assume “James Java” has had a change of heart and wants a legal name change to go with it, so select him from the list, and when he comes up, select Edit. Notice the UI will change to make his name editable, so let’s change it to “James Clr.” Click Save, and you’re back to a read-only UI. Let’s go back and see the list of students again, so select the Home icon (the house in the lower-left corner), and you’re back to that starting menu again. You could go looking for James by selecting Menu | All Students again, but the clipboard icon shows you a list of all the objects you’ve used recently. Select it and, sure enough, “James Clr” is there. (The “Student” there is the type of object James happens to be. That’s not important in a demo that only has one kind of object, but as the system grows, so will the chances that objects named James might be both a Student and a RegistrationHistory, for example.)

Students and Studying

The Student model seems pretty anemic—students are more than just a name! They’re also a subject, so let’s add that to the model. Stop Visual Studio, and open up the Student.cs file in the Template.Model project. Student currently looks like the code shown in Figure 1.

Figure 1 The Basic Student Type

using NakedObjects;
namespace Template.Model
  public class Student
    // All persisted properties on a domain object must be 'virtual'
    NakedObjectsIgnore] // Indicates that this property
                        // will never be seen in the UI
    public virtual int Id { get; set; }
    [Title]// This property will be used for the object's title at
           // the top of the view and in a link
    public virtual string FullName { get; set; }

Add a new property to Student, say “Subject,” also a string, and also public and virtual, and then punch F5 again. Thanks to the development-default settings in EF, James Java will lose his name change, but notice what you’ve gained: Throughout the UI and the database, you now have students who have subjects. All of them are currently empty, mind you, but then again, lots of college students have no idea what they’re studying, either. The larger point is that with that single property, you’ve gained complete UI support, as well as database support, without having to write any code to create the UI, validate the input, or persist the data.

Wrapping Up

There’s obviously a lot here that I’m just skipping over, and it would be teasing to not explore it further, so I’ll spend a few articles examining NOF and determining what its limitations are. The important point is that particularly for applications that aren’t consumer-facing, not everything has to be a hand-crafted artisanal UI and database; sometimes the speed with which an application can be generated is far more important than how pretty it looks. NOF and other DDD-inspired kinds of tools can be exactly what the doctor ordered in those kinds of situations, and you even have some room to make things “prettier” by building a more customized Angular (or other SPA framework) front end. Next time I’ll explore some of the options and capabilities of domain classes in NOF, and we’ll see just how well NOF can handle common UI concerns. In the meantime … Happy coding!

Ted Neward is a Seattle-based polytechnology consultant, speaker and mentor. He has written a ton of articles, authored and co-authored a dozen books, and speaks all over the world. Reach him at ted@tedneward.com or read his blog at blogs.tedneward.com.

Discuss this article in the MSDN Magazine forum