Wednesday, October 31, 2007

Understanding Domain Models - One Concern at a Time

At one point during the Domain-Driven Design book club meeting yesterday, we had confusion about distinguishing between Entities and Value Objects.

For example, database persistence of both Entities and Value Objects can be done in the same way, sometimes even using an ID column for Value Objects (even if that was unnecessary.) Moreover, caching can be done for Entities too, which seemed to further decrease the distinction between Entities and Value Objects.

I had to interrupt the talk for a second and emphasize my preference to first understand the essence of Entities and Value Objects independently of Persistence. The architect thought it would also help to take Caching out of the equation. Afterwards, our discussion got to the heart of the matter without the peripheral concerns, and we were able to descern the true domain-level differences between Entities and Value Objects.

The point of this is when thinking about the domain model, it is easier to understand how it fits with the business by leaving other (usually technological) concerns out of the equation, at least temporarily. Once there is a good understanding of how the domain model fits the business (e.g. agreeing that States will be treated as Value Objects or Customers will be treated as Entities), each of the other concerns can be focused on and addressed separately (e.g. persistence, caching, etc...)

Tuesday, October 30, 2007

Entities and Value Objects

Today, we had a book club meeting at work for Domain-Driven Design by Eric Evans. While discussing the differences between Entities and Value Objects, we came to these conclusions:

  • Entities naturally represent business entities (e.g. Customer, Order, Payment.) Value Objects are used as descriptors of business entities (e.g. Name, Color, Age.)
  • Entities have a strong continuing thread of identity that needs to be well established sometimes by having an extra ID field or a universal ID when transferred across multiple systems. Value Objects are easily identifiable based on their values, and can be easily passed around and used across systems due to that.
  • Entities are normally mutable, and thus incur synchronization overhead when multiple copies are modified across different systems. Value Objects are immutable, which makes them easy to cache and improve performance.

Let us know in the comments area if you know of other differences or if you ever made a conscious effort to make the distinction between Entities and Value Objects.

Monday, October 29, 2007

Necessary Compromise or Unnecessary Surrender?

Four months ago, I had a discussion with a developer about a need for a new Eclipse RCP Table widget that facilitates multi-row selection for novice computer users.

One solution was to use one of the check-box based tables that allow you to select multiple rows by checking them one by one. Once you have a group of selected rows, you can then right-click on one of them and select an operation (delete, print, etc...), and it will be performed on the whole group. If you right-click on an unselected row however, the whole row gets highlighted and you get to perform operations on that single row.

The design seemed good enough for our needs, but it raised a big concern about whether it would satisfy expert users that prefer to hold the shift button and click on a row to make large-scale selections. After some discussion and brainstorming, we ended giving up on the idea all together and reverting back to the traditional Table widget.

I was not satisifed however and kept believing that if we persist in designing a Table widget that would satisfy both novice and expert users, we would eventually reach our goal with little compromise.

Indeed, upon checking the checkbox Table widget in GMail, I discovered that they solved the problem by allowing expert users to first check a row, and then hold SHIFT while clicking within the checkbox area of another row (instead of clicking on the row itself), ending up checking all rows in between.

The lesson learned was that when a decision on something involves a compromise, always double-check it to see if the compromise is truly necessary or is an otherwise unnecessary surrender to the situation. By being super-optimistic about achieving your requirements regardless of the obstacles on the surface, you may often figure out a way to have it all with minimal compromise.

Thursday, October 25, 2007

First look at JFace Data-Binding 3.3

I took a look at the JFace Data-Binding framework that shipped with Eclipse 3.3 Europa, and was delighted to find a number of improvements over the older provisional version that was released with Eclipse 3.2 Callisto.

What is data-binding though?

The basic use-case of Data-binding is to synchronize the contents of user-interface widgets (e.g. text boxes, labels, etc...) with properties on domain models bidirectionally, primarily by relying on the Mediator and Observer Design Patterns from the Gang of Four, shielding the developer from the details.

For example, if you data-bind a text box to the name of a person, then whenever you modify the text box contents, the new value is automatically copied to the name property on the person model. In the same token, if the name on the person model gets modified programmatically, it gets automatically copied to the text box on the screen.

Here is some code to demonstrate how to do that with JFace data-binding:

Person person = new Person();
Text nameTextBox = new Text(composite, SWT.BORDER);
DataBindingContext dataBindingContext = new DataBindingContext();
dataBindingContext.bindValue(SWTObservables.observeText(nameTextBox, SWT.FocusOut), BeansObservables.observeValue(person, "name"));

Of course, the Person model has to have an addPropertyChangeListener method and a name setter that fires property changes according to the JavaBean spec:

public void setName(String name) {
  String oldValue =; = name;
  propertyChangeSupport.firePropertyChange("name", oldValue, name);

One of the biggest differences in the new JFace Data-binding framework is the binding syntax:

dataBindingContext.bind(text, new Property(person, "name"), null);

dataBindingContext.bindValue(SWTObservables.observeText(nameTextBox, SWT.FocusOut), BeansObservables.observeValue(person, "name"));

Does that make you wonder if it's less user-friendly than the older syntax?

The benefit of the new syntax is realized in the method signature. The older bind method had Object in its signature parameters, so you could have made mistakes when invoking it. Therefore, the signature did not guide programmers about which parameters to pass.

The new API has bindValue and bindList to separate between them. The signature of the new bindValue only takes ObservableValue objects, which are easily created in factories like SWTObservables or BeansObservables. That restricts the parameters that can be passed

The observeText method takes any Control however, and I had problems realizing that I was supposed to only use observeText(Control, int) instead of observeText(Control) when observing a Text widget. I would like these methods to be more guiding to the developer with their signature. This can be done by having observeText, observeLabel, observeSpinner, etc... that have the exact widget they support in their signature (e.g. observeText(Text, int))

The cost of using the new 3.3 API is a much more verbose syntax that again makes me wonder if it is easier to just write observers myself to handle two-way synchronization for simple cases.

Nonetheless, JFace Data-binding lets you customize the way data flows from the widget to the model and vice versa using UpdateValueStrategy objects. This helps with more complex use-cases of data-binding when you would like life-cycle events to occur before or after a value is copied to the widget or model. Examples would involve data-conversion and business validation.

Still, I believe we need a simpler syntax for simple cases, which usually constitute about 80% of all use-cases. I look forward to seeing that being taken care of in future versions of JFace Data-Binding.

Myth of Maintainability/Performance Trade-off

Reading through blogs and technology books, I remember an architect mentioning that he always liked to build code according to criteria in this order:

  1. Functional: It must do the job or else it is useless.
  2. Maintainable: Code lives most of its life in maintenance mode, so we may as well make it maintainable to ease performing code changes, bug fixes, and feature additions.
  3. Performant: If it does not get the job fast enough, why bother use the program at all?
However, I have seen developers struggeling with performance issues trash maintainability in favor of performance, not believing that they can come up with a solution that would achieve both.

I beg to differ. I believe that with today's hardware, no matter what the performance optimization is, it can almost always be abstracted and encapsulated in a way that would keep the application layer code clean. I notice that programmers who end up achieving both maintainability and performance are the ones that keep both goals in their head while solving performance problems. On the other hand, those who soly focus on performance may end up trashing maintainbility, and they feel justified and happy about it, possibly cursing at frameworks, not knowing that they probably could have had both performance and maintainability if they made that a goal instead of taking a defeatist attitude towards it.

If you could think of a scenario in a recent project where a lot of maintainability had to be sacrificed for performance, please share in the comments area for discussion.

Tuesday, October 23, 2007

SWT is RESTful

According to the recent O'Reilly book RESTful Web Services, REST is a set of design criteria that are very general, and not particularly tied to the Web.

Nothing about REST depends on the mechanics of HTTP or the structure of URIs

One of the main criteria for a RESTful architecture is having a unified API regardless of which business problem is being solved. For example, HTTP is known for having the operations put, post, get, delete, and a few others. As long as it is used in that way, the application architecture is RESTful because its API is predictable regardless of the use cases.

I saw JavaBeans cited as an example. After all, every JavaBean can be introspected for available properties, and then you can always perform a set or a get on a particular property.

What is the benefit of this? Well, for HTTP, it enables all web browsers and different clients to work with RESTful web services (though browsers are generally limited to the get and post operations) For JavaBean, all Java tooling applications can work with any JavaBean without having to learn its particular API.

That brings me to SWT as an example. My colleague from a previous project, David Orme, always emphasized that SWT widgets must have a constructor that takes (parent, style) arguments. In fact, this is strongly recommended even for building custom widgets. Why? Because, this is what most SWT automated tools expect, such as the Visual Editor, and other GUI building tools. So, to make custom widgets usable by the widest range of clients, they better follow the same design in their constructor.

In conclusion, I would say that SWT is RESTful in the same way HTTP and JavaBeans API are.

Monday, October 22, 2007

Learning Design Patterns

A colleague of mine felt that Design Patterns are complicated and difficult to remember. He was wondering about how to learn Design Patterns in a way that would stick in his mind till the time comes to use them.

My motto for this has always been "Use it or Lose it."

When I first learned Design Patterns in my undergrad degree, I thought they were cool, but did not appreciate their full value and did not really get when to apply them and when not to. Naturally, due to not using them for a while (except for occasional use of singletons and observers,) I forgot many of them and was not able to detect the need for them when it arised.

Later when I was doing my graduate degree, I had the pleasure of relearning Design Patterns from a great instructor at DePaul University. That was when Design Patterns really clicked in my mind. A number of factors that contributed to that were the instructor's great emphasis on practical benefits to applying Design Patterns in real-world applications, my healthy-skepticism and asking of many questions, and the exercises that gave us the opportunity to apply Design Patterns whenever we learned them in order to better fulfill business requirements for maintainability and extensibility in real-world scenarios.

I was so excited about Design Patterns after taking that course that I started applying them at work on a new project and reaped great benefits from them. The use of Design Patterns like Decorator, Command, and Template Method helped create very flexible, maintainable, and extensible code for the ever-changing requirements that I had. The feeling I had whenever I received requirement changes and was able to incorporate them in practically no time due to the earlier application of patterns was absolutely exhilirating. From that point on, there was no turning back for me as I experienced first-hand the true benefits of Design Patterns on a real business application.

On later projects, I attempted to apply every Design Pattern that seemed to fit the problem at hand. That got me first-hand experience on many different Design Patterns and allowed me to truly learn when they provided value and when they did not. Additionally, more Design Patterns stuck in my mind due to having had first-hand experience of applying them.

Did I ever over-engineer? Of course. Do I regret applying the Design Patterns that caused that? Never. If you hold the pendulum in one side (lack of enough engineering) and never let it swing to the other side (over-engineering), you would never give it a chance to pass through the middle (just-enough engineering) and stabalize there eventually. In other words, If I had not tried new Design Patterns in the first place because of fear of over-engineering, I would not have realized their benefits later when I did successfully employ them in situations where they provided great value. Besides, that also helped stick them in my mind for future use.

So, what is the best way to learn Design Patterns and have them stick?

  1. Study them with a genuine interest to deeply understand them and recognize when applying them would reap you benefits in real-world scenarios. My best recommendation for a book is Head-First Design Patterns because of its visual style, great humor, and deep tying of Design Patterns to Object-Oriented Design principles, which are the foundations on which Design Patterns were built. However, other great books are: Design Patterns Explained, Applying Patterns and UML, Refactoring to Patterns, and Design Patterns: Elements of Reusable Object-Oriented Design.

  2. Early in the learning process, look for every opportunity to apply one of the Design Patterns. Keep a Design Patterns book next to you to refer to whenever you are designing new Object-Oriented code. That way, you can always check if a Design Pattern could help with the problem at hand, and thus get an opportunity to exercise it. In no time, you will develop a sense of smell for patterns and become able to detect the need for them instantly when it emerges without the need for a book.

  3. Once you realize the benefits of a Design Pattern in a particular scenario, learn to focus in the future on recognizing when the Design Pattern is absolutely necessary and when it is just over-engineering. This is the stage of learning in which you start balancing the pendulum back in the happy middle. You don't want the pendulum stuck at either end after all.

Sunday, October 21, 2007

Pain and Pleasure

Do you ever wonder how much a programmer's personality contributes to writing good code? I noticed that the more pain a programmer can tolerate, the worse his code is.

For example, some people can tolerate Java code like this:

getHibernateTemplate().execute(new HibernateCallback() {
  public Object doInHibernate(Session session) {
    Customer customer = new Customer("Eitan");

Others would shudder at the sight of extra brackets and noisy use of the callback, and thus push the callback into the framework or a super class to get something like this:

Customer customer = new Customer("Eitan");

I also noticed that the more sensitive a programmer is to pain, the more sensitive he can be to pleasure too. Sensitive programmers tend to paint beautiful pictures in code because they can better sense beauty in certain patterns of writing code.

What does sensitivity boil down to though? Can a programmer develop his sensitivity further? Well, I believe that sensitivity stems from awareness and focus on how maintainable and readable code is. The more attention a programmer gives to these aspects, the more he will feel pain in badly written code and pleasure and very easy to read code.

In other words, keep code readability and maintainability at the back of your mind, and you will be able to develop your sensitivity further.

Saturday, October 20, 2007

Birthday Code Gifts

Yesterday was my birthday. Here are code gifts that I got:

Ruby:! cake -- Nick

Java: Cheers Andy! I was trying to come up with Java version of Nick's greeting, but it was already getting too long, and I hadn't even started the unit test. Shoot, I should have written it first, huh -- Fred

Scheme: (cons (car cake) andy-mouth) -- Ryan

Haskell: The Haskell version would involve asserting a world such that there is already a piece of cake in Andy's mouth. -- Fred

DHTML: And in DHTML you would set up an oncake handler for Andy's mouth. -- Fred

Thank you guys!!! Best gifts I got in years. ;)