Friday, October 26, 2007

The Fail Fast Rule

Every time you're writing a piece of code and you have to deal with unknown corner cases ...
Every time you're implementing some kind of logic and you don't know what to do when things go bad ...
Every time you think: this can never happen, I don't have to check for it ...
Every time you don't know what to do or what would happen ...
Please ...

Fail fast.

This is the Fail Fast Rule, as I call it, a term borrowed from the Java Collections iterators behavior:

Every time your code might fail, and you don't know what to do, just make it fail abruptly.

That is: do not ignore it, do not (just) log it, but let your code throw an exception.

An example was how we computed a shopping cart total in one of my previous posts:

public class ShoppingCart {

private static final int MAX_TOTAL = 10000;

private List orders = new ArrayList();

public void addOrder(Order o) {
this.orders.add(o);
}

public double computeTotal() {
double total = 0;
Iterator it = this.orders.iterator();
while (it.hasNext()) {
Order current = (Order) it.next();
total += current.computeSubTotal();
if (total > MAX_TOTAL) {
throw new SomeException();
}

}
return total;
}
}

As soon as the total gets too high, an exception is thrown. Probably this will change later, because we may want to handle it more gracefully, but in the meantime: make it fail.

Why?

Because if an exception will pop up in front of you, you'll have found a bug, a corner case, something that you have not still properly implemented or that you have not thought of.

So remember: make it good, or fail fast.

Tuesday, October 23, 2007

JavaMail and GMail : it's all about configuration

Yesterday I spent a couple of hours trying to send emails with JavaMail APIs via my GMail account.

It wasn't easy: the standard JavaMail configuration didn't work, while Google gave me a lot of wrong and/or outdated information.
Moreover, JavaMail FAQs provide a sample about sending emails via GMail, but it has some problems too.

So I think these bits of information will be helpful to someone trying to accomplish the same task ...

The problem is that GMail uses TLS and the STARTTLS command.
The solution applies to JavaMail 1.4 and JDK 1.4 or higher and is just a matter of configuration.

First, and obviously, enable POP support for your GMail account.

Then, put the following configuration in your properties file:

mail.transport.protocol=smtp

mail.smtp.host=smtp.gmail.com

mail.smtp.starttls.enable=true

mail.smtp.auth=true

mail.user=<your_username>

mail.password=<your_password>

The key point is the part in bold: enabling the STARTTLS command.
That's the tricky part.
Once created the properties file above, just configure your JavaMail Session object and send your mail message as you'd always do:


Properties props = ...; // <-- Your properties above

Authenticator authenticator = new YourAuthenticator(...);

Session session = Session.getInstance(props, authenticator);

Transport t = session.getTransport();

t.send(yourMail);


That's all.
Feel free to comment on for any question.
Enjoy it!

Friday, October 19, 2007

Avoid your getters and setters, Part 2

More than one year ago we've talked about how to avoid getters and setters by using the most fundamental object oriented programming principle: programming to an interface.

Well, it was just the beginning ...

I know we're a bit late, but let's go now with the second part of my
How to avoid getters and setters series ... I hope you'll enjoy it!

Avoid your getters and setters : The Expert, the Aggregate and the Value Object.

Many people use getters and setters so extensively because don't really get the importance of correctly assigning object responsibilities and behaviors.

So, in this second part we'll mix together GRASP and
Domain Driven Design patterns, in particular:
We'll see how wrongly managing responsibilities and behaviors, while abusing getters and setters, can lead to a corrupted business domain, and how the patterns above will help you to correctly address these kind of problems.

The business domain.

Let's start our discussion by showing a simple business domain.
We're implementing yet another ugly e-commerce system, so we have a shopping cart holding a number of orders, each refer
ring to a given product.
Without going further on, let's restrict our domain model to three simple entities: ShoppingCart, Order and Product.









A
ShoppingCart can hold one or more Orders, and an Order refers just to a single Product.
Moreover, we have some simple business rules regarding these entities:
  1. The ShoppingCart total is the sum of all Order sub-totals.
  2. Each Order sub-total is the Product price times the ordered Product quantity.
  3. The ShoppingCart total cannot exceed the value of EUR 10000.
Pay particular attention to the latest point: it is an invariant, a rule that must be always kept valid.

That's all.
Very simple, isn't it?

Let's implement it : the wrong way.

The entities and rules above can be straightforwardly implemented as follows:

public class Product {

private String name;

// ...

private double price;

// ...

public double getPrice() {
return this.price;
}

public void setPrice(double price) {
this.price = price;
}
}

public class Order {

private Product product;
private int quantity;

public Product getProduct() {
return this.product;
}

public void setProduct(Product p) {
this.product = p;
}

public int getQuantity() {
return this.quantity;
}

public void setQuantity(int q) {
this.quantity = q;
}
}

public class ShoppingCart {

private List orders = new ArrayList();

public void addOrder(Order o) {
this.orders.add(o);
}

public List getOrders() {
return this.orders;
}
}
As you can see, all classes have the right properties and dependencies:
  1. A Product has a price.
  2. An Order refers a Product and has a product quantity.
  3. The ShoppingCart has more orders.
  4. The ShoppingCart total can be calculated by iterating all Orders and summing up each Product price times the ordered product quantity.
However, this design (and implementation) is seriously flawed:
  • There's no clear assignment of responsibilities and behaviors.
    • Hence, it is full of getters and setters.
      • Hence, there's no encapsulation.
        • Hence, all business logic is external.
          • Hence, it is easy to corrupt domain state and violate business rules.
How?

Given our design and implementation, the following code is absolutely legal:

Product p1 = new Product();
Product p2 = new Product();

p1.setPrice(1000);
p2.setPrice(2000);

Order o1 = new Order();
Order o2 = new Order();

o1.setProduct(p1);
o1.setQuantity(5);

o2.setProduct(p2);
o2.setQuantity(5);

ShoppingCart cart = new ShoppingCart();

cart.addOrder(o1);
cart.addOrder(o2);
But hey, wait!
The ShoppingCart total is now EUR 15000!
That's because the business logic is computed outside of the object that holds the information; so let's solve this problem by introducing the
Information Expert pattern.

Refactoring toward the Expert.

The Information Expert pattern is part of the
General Responsibility Assignment Software Patterns (GRASP), and states the following:
Assign a responsibility to the information expert: the class that has the information necessary to fulfill the responsibility.
We have two responsibilities to relocate:
  • The shopping cart total computation: here, the information expert is the ShoppingCart class.
  • The order sub-total computation: here, the information expert is the Order class.
By relocating the two responsibilities we'll improve our encapsulation and make our implementation more robust, because the ShoppingCart will be able to check that the total doesn't exceed EUR 10000.

public class Order {

private Product product;
private int quantity;

public void setProductWithQuantity(Product p, int q) {
this.product = p;
this.quantity = q;
}

public double computeSubTotal() {
return this.product.getPrice() * this.quantity;
}
}

public class ShoppingCart {

private List orders = new ArrayList();

public void addOrder(Order o) {
this.orders.add(o);
}

public double computeTotal() {
double total = 0;
Iterator it = this.orders.iterator();
while (it.hasNext()) {
Order current = (Order) it.next();
total += current.computeSubTotal();
if (total > MAX_TOTAL) {
throw new SomeException();
}
}
return total;
}
}
As you can see, the ShoppingCart computeTotal() method is now able to check against the maximum total, and throw an exception if there's something wrong, avoiding domain state corruption.

However, there's still something wrong; take a look at the following code:

Product p1 = new Product();
Product p2 = new Product();

p1.setPrice(1000);
p2.setPrice(2000);

Order o1 = new Order();
Order o2 = new Order();

o1.setProductWithQuantity(p1, 2);
o2.setProductWithQuantity(p2, 4);

ShoppingCart cart = new ShoppingCart();

cart.addOrder(o1);
cart.addOrder(o2);

cart.computeTotal();

// !!!!!!!!! DANGER !!!!!!!!!!
o1.setProductWithQuantity(p1, 3);
// !!!!!!!!! DANGER !!!!!!!!!!
The problem is that we can always change the Order product and quantity, changing so the shopping cart total without preventing it to enter in an invalid state!

Where's the
real problem?
How to solve it?

Refactoring toward the Aggregate and the Value Object.

The real problem is that we are interested in keeping the ShoppingCart state always correct, that is, in keeping its invariants: however in the current design and implementation we are not able to control everything happens inside the ShoppingCart, because we can directly modify its Orders without going through it!

The solution is to apply the Aggregate and Value Object patterns, part of the
Domain Driven Design.

An Aggregate is a set of related objects whose invariants must always be kept consistent, and an Aggregate Root is an object that acts like the main access point into the aggregate; all access must go through the root, and objects external to the aggregate cannot keep references to objects contained into the aggregate: they can keep a reference only to the aggregate root.

A Value Object is an object that has no identity and is immutable: it is equal to another value object of the same type if its properties are equal too, and must be discarded if its properties need to change.

How to turn this theory into practice, applying it to our domain?

First, our ShoppingCart and Order are part of an aggregate.
It's easy: the "EUR 10000" invariant involves both objects, so it must be kept consistent across the two.
Moreover, Orders make sense only if related to a ShoppingCart, so no one should access an Order without first going through a ShoppingCart: this means that the ShoppingCart is the root of the aggregate.

Second, the Order is a Value Object: it doesn't make sense to create an order and change its related product and quantity during its life cycle; an order always refers to the same product with the same quantity, and if something needs to be changed, it must be discarded and a new one must be created.

Now let's refactor our previous code:


public class Order {

private Product product;
private int quantity;
private double subTotal;

public Order(Product p, int q) {
this.product = p;
this.quantity = q;
this.subTotal = this.product.getPrice() * this.quantity;
}

public double computeSubTotal() {
return this.subTotal;
}
}

public class ShoppingCart {

private List orders = new ArrayList();

public void addOrder(Order o) {
this.orders.add(o);
}

public boolean removeOrder(Order o) {
return this.orders.remove(o);
}

public double computeTotal() {
double total = 0;
Iterator it = this.orders.iterator();
while (it.hasNext()) {
Order current = (Order) it.next();
total += current.computeSubTotal();
}
return total;
}
}

The Order class is now immutable and part of an aggregate together with the ShoppingCart.
The ShoppingCart is now the aggregate root, and every change to its Orders must go through it.

Now, you have no way of corrupting your domain.

Remember: the Expert, the Aggregate and the Value Object.
Who do you want to be?

Saturday, October 13, 2007

Alive

Hi all.

I'm not going to talk about the great Pearl Jam song.
I'm going to talk about me, because (very) long time has passed since my last post, and yes ... I'm still alive.

I don't want to bother you too much, just let me jumble a few bullet points about the most important things happened to me during these months:

  • I finished working at that big project for RAI, the Italian State Television, involving the design and development of its main portal. It was a very interesting experience and I think I'll write more about things I learned (because we always learn), in the future.
  • I became a committer of the Taconite Ajax Framework, improving my Javascript skills and working with CSS Selectors.
  • I've been at Spring One 2007 and it was nice, even if it didn't fulfill my high, maybe too high, expectations.
  • I bought a white MacBook and I'm really happy with it.
  • I've started working at (and I'm still doing) clustering a famous Open Source Enterprise product: I cannot say more right now, but I think more news will pop out soon.
  • Spring Modules approached the 0.8 release and will (hopefully?) soon approach the 0.9 one.
  • I've changed houses, and I'm really happy in the new one.
  • Radiohead released their new album, after about four years of silence ... and I suddenly bought it.
  • ... I've started blogging again ... seriously!
That's all.
Now let the thoughts flow again.
Now let the fragments burst in the air.

Sunday, January 21, 2007

Join Us: Be Commons-Logging Free!

Johannes invited his readers to revise their code in order to remove all dependencies on Jakarta Commons-Logging (JCL).

Why?
It is simple: JCL gives you a lot of class loading problems, often driving you mad.
If you've never had class loading problems while deploying your Simple Servlet / Complex JEE application which makes use of JCL, if you've never struggled for making JCL use that damn Log4j configuration file, you're surely one of the luckiest person in the world, so hurry up and go buying that lottery ticket!

That's way I always use, at least when possible, raw Log4j loggers.

However, thanks to Johannes I've discovered SLF4J: I gave it a try and in less then two minutes I've migrated my current project from JCL to it!
And what's most important : it rocks!

So, again: join us and be Commons-Logging free!

Tuesday, January 16, 2007

Five things you don't know about me

Some weeks ago I've been tagged by Daniele , but I'm very busy to do anything other than working at a big project for RAI .
So, now, let me start the new year with five things you don't know about me:

  • I used to practice martial arts: more specifically, Shorinji Kempo.
  • I used to play guitar in a Rock band called Voodoo Economics.
  • I used to write short novels, and I also won a prize.
  • I have very little spatial ability and I often lose my way (literally).
  • My nickname, Tourist, is related to the homonym Radiohead song: The Tourist.

This silly thing has to have an end ... so here it is!

Sunday, December 10, 2006

Spring Modules 0.7 and XT Framework Highlights

Hi guys,

I'm pleased to announce here the new Spring Modules 0.7 release.
We have made several changes (you can find the general changelog here), so I suggest you to update to the new release.

Talking about the XT Framework, here is a short list of the most important changes:

XT Modeling Framework :

  • New annotations for better controlling the DynamicBeanIntroductor behaviour.

XT Ajax Framework :

  • Enhanced integration with Prototype and Scriptaculous JavaScript libraries (in particular, full support for effects and drag and drop).
  • New components, in particular the JspComponent, which let you dynamically send JSP contents through Ajax.
  • Support for mapping more Ajax handlers to the same web path.
  • Enhanced DefaultValidationHandler, for easy Ajax validation.

Take a look at the whole XT documentation for a full taste of all XT Framework features ... any feedback will be very welcomed!

As a final, yet important, note, I'd like to thank all the Spring Modules community, and all Spring Modules developers: it's always a pleasure to work with keen guys!

Friday, December 08, 2006

Spring 2.0 and the P-Namespace

Some days ago Rod Johnson blogged about an undocumented feature of Spring 2.0: the so-called P-Namespace, which permits you to shorten the XML configuration.
This feature has been very well welcomed by the developers community, because it clearly makes the Spring XML configuration easier to manage and read, without running into the burden of writing a custom namespace handler.

I strongly suggest you to give it a try.

As a consequence, many people started asking more, and in particular many people I know asked about the possibility of applying the same kind of configuration to collection and map properties.
Too bad, this seems to be impossible, but I'm here for giving my two cents about another (documented) way of configuring collections, that is IMHO easier to read. It uses the P-Namespace and the util schema, here is a sample:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:p=" http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-2.0.xsd">

<util:set id="contents">
<bean id="c1" class="org.acme.Content" p:name="c1"/>
<bean id="c2" class="org.acme.Content" p:name="c2"/>
<bean id="c3" class="org.acme.Content" p:name="c3"/>
</util:set>

<bean id="container" class="org.acme.Container" p:name="container" p:contentList-ref="contents"/>

</beans>

As you can see, you have to simply configure your collection with the util schema (that makes it reusable, too), and then inject it with the P-Namespace!

I hope you'll find it useful!

Friday, November 24, 2006

Maven2 : Evil or Not?

Guys, I have very little time to blog these days, too much work, but let me do a complaint.

Since my colleague Gianugo talked me about it, I've always been a strong supporter of Maven2.

It is true that it is a kind of black magic.
It is true that it has a (very) poor dependencies conflict resolver.
But hey, it let you manage your build process with very little configuration effort, has a good convention over configuration approach, let you centralize your dependencies, has a wide community and ... is cool (should I have mentioned this as first?).
So, since I started to use it, I have to say it helped me very much in speeding up my build management process.

But please, guys: can someone tell me why there are tests that succeed when executed by my preferred IDE, and fail when executed by Maven2?

Weeks ago I've already discovered serious problems between Maven2 and static inner classes, but now I can't really find any workaround.

Some times ago my colleague Ugo Cei started blogging about the question: Goolge: evil or not?

Now it is my time: Maven2 : evil or not?

Tuesday, October 31, 2006

Java Interfaces or Abstract Classes?

These days there's a very interesting discussion on the Domain-Driven Design mailing list about the use of "pure" Java interfaces (the one expressed by the interface keyword) or classic abstract classes for modeling and implementing domain objects.

I strongly suggest you to read the whole thread.

But for now, let me summarise a bit.

I'm a strong supporter of the use of interfaces in domain model.
As I already explained in one of my old posts, my main point is that pure interfaces let you clearly separate the business behaviours and contracts from implementation details. In particular, they let you clearly express what is the published interface, and what the public one: this enables you to write code that depends only on interfaces that actually express domain concepts, without worrying about implementation-only methods.
As a side note, interfaces let you easily test your system.

Those that prefer to use abstract classes argue instead that interfaces cannot fully express domain contracts, because they are just "signatures with no body", while abstract classes carry an implementation and so are able to express those missed contracts.
Moreover, they mainly see interfaces as a way of enabling multiple implementations/inheritance: if no multiple implementation is needed, there's also no need for an interface.
Finally, they think interfaces ara against evolutionary design because evolving the design by adding a method to an interface breaks all implementors.
Following their point of view, so, interfaces for domain objects are mostly just one more indirection, just one more useless source file.

I fully understand their points, but I disagree with many of them.
I obviously cannot say that the pure interfaces approach is absolutely better than the other: everything has pros and cons, but I still prefer it.
It is not because using abstract classes is wrong.
Too bad, I think there's a base misunderstanding between the two. Trying to clarify, I'd like to highlight the following points:

  • It is true that you cannot fully express all you contracts using just interfaces: in fact, I suggest to use interfaces plus abstract classes, or eventually AOP aspects expressing business contracts.

  • Programming by "pure" interfaces doesn't mean you have to make an interface for every class: it just means you have to make an interface for main business concepts whose interface methods will be referenced in your code.

  • When you program by ("pure") interfaces and you are in the situation where you need to add a method in your interface, if that method doesn't fit into all implementors, this means that you have wrong interfaces and you need refactoring. This is because the adding of a method into an interface must be driven by its contracts, and if an implementor doesn't need that method, it may be that the implementor should not have that interface.

  • Pure interfaces are not against evolutionary design, because you can introduce them inch by inch in your design and use refactoring for supporting changes.



That said, I'd like to hear your thoughts, my reader ... any opinion?

Wednesday, October 18, 2006

Integrating Prevayler into Spring: ease your persistence with Prevayler-Template.

System prevalence is a term coined by Klaus Wuestefeld, denoting a transparent persistence solution.

Let me give some more details for understanding what that means.

A prevalent system is a system made of business objects which obey the following rules:

  • They must be serializable.

  • The must be deterministic, that is, given some input to a business method, it must always return the same output.


A prevalent system is always fully kept in RAM and data is persisted through object serialization, by wrapping all business operations into command objects, serializing commands and all contained business objects into a log file, and executing them.
Then, when the system recovers after shutdown, all commands are read from the serialized log and executed again, recreating a perfect replica of the system prior to its shutdown.
This makes your system (and all its business objects):

  • Persistent, thanks to object serialization.

  • Transactional, because each command represent a single transaction and is executed in isolation.

  • Incredibly fast!



This is just a short (and partial) introduction: more details can be found here and here.

Prevayler is a Java, Open Source, implementation of a framework for achieving system prevalence.
It is widely used in environments where classical persistence solutions are not suitable or unwanted.
Moreover, it is simple to use, but requires you to sligthly change the way you code your application, because:

  • Many applications use the well-known Data Access Object (DAO) pattern for implementing persistence layer logic, while Prevayler (as the prevalence concept dictates) uses plain command objects and requires you to wrap your business methods with them, removing the need of a pure data access layer.

  • You have to care about the infamous baptism problem.



The Spring Prevayler-Template project aims at solving these problems, by providing a Prevayler-based implementation of the DAO pattern and the Spring Data Access architecture used for ORM frameworks, which let you create a prevalence system with totally transparent business objects persistence by simply respecting the rules above, common to all prevalence systems, and by:

  • Adding an (automatically managed) identifier property to your business objects.

  • Implementing a standard Data Access Object, as you would do with Hibernate or alike.

  • Configuring it into the Spring application context.


No additional code, no mappings, no annotations ... nothing more.

Let me show you a concrete example.

First, take a bunch of business objects, say a Person, an Employee and a Company:


public interface Person extends Serializable {

public void requestEmployment(Company company);
}


public interface Employee extends Person {

public void workAsAMad();
}


public interface Company extends Serializable {

public void employ(Person person);
}



Then, implement your business objects and assign them a simple identifier property:


public class PersonImpl implements Person {

private Long id;

public void requestEmployment(Company company) {
// ...
}
}


public class EmployeeImpl implements Employee {

private Long id;

public void workAsAMad() {
// ...
}
}


public interface CompanyImpl implements Company {

private Long id;

public void employ(Person person) {
// ...
}
}



That's all you need to do with your business objects.

Now, let us write a Data Access Object using the PrevaylerTemplate.
The classes showed below are a Prevayler-based porting of the well-known Hibernate generic DAO:


public interface IGenericDao<T, PK extends Serializable> {

public PK create(T newEntity);

public void update(T entity);

public void delete(T entity);

public T read(PK id);
}


public class PrevaylerGenericDao<T, PK extends Serializable> implements IGenericDao<T, PK> {

private PrevaylerTemplate prevaylerTemplate;
private Class<T> entityType;

public PrevaylerGenericDao(Class<T> type) {
this.entityType = type;
}

public PK create(T newEntity) {
this.prevaylerTemplate.save(newEntity);
return (PK) newEntity.getId();
}

public void update(T entity) {
this.prevaylerTemplate.update(entity);
}

public void delete(T entity) {
this.prevaylerTemplate.delete(entity);
}

public T read(PK id) {
return (T) this.prevaylerTemplate.get(this.entityType, id);
}

public PrevaylerTemplate getPrevaylerTemplate() {
return prevaylerTemplate;
}

public void setPrevaylerTemplate(PrevaylerTemplate prevaylerTemplate) {
this.prevaylerTemplate = prevaylerTemplate;
}
}



As you may note, the PrevaylerTemplate is used as it were a standard, maybe Hibernate based, data access template.

Finally, you need to configure it:


<bean name="prevalentSystem" class="org.springmodules.prevayler.system.DefaultPrevalentSystem">
<property name="prevalentClasses">
<list>
<value>Person</value>
<value>Company</value>
</list>
</property>
</bean>

<bean name="prevaylerConfiguration" class="org.springmodules.prevayler.configuration.PrevaylerConfiguration">
<property name="prevalentSystem" ref="prevalentSystem"/>
<property name="prevalenceBase" value="classpath:testPrevalenceBase"/>
</bean>

<bean name="prevaylerTemplate" class="org.springmodules.prevayler.PrevaylerTemplate">
<property name="configuration" ref="prevaylerConfiguration"/>
</bean>



There are just three objects to configure:

  • The prevalent system, defining the prevalent system implementation to use for storing your business objects. It requires you to configure the list of prevalent classes in the system, that is, the classes of business objects to persist. Note that if you need to persist a whole hierarchy, you need to specify just the base class, as it is in the sample where we configured just the Person class.

  • The prevayler configuration, defining the prevalent system implementation to use, and the location of the directory where Prevayler logs will be saved.

  • The prevayler template, defining its associated configuration bean.



That's all ... now your business objects are ready to be persisted!
And if you need to persist a new business object, just add its class to the prevalent classes configuration and do no more!

Prevayler-Template is a new born Spring module, currently available here into Spring Modules sandbox.
You can also take a look at Prevayler-PetClinic, the Prevayler-Template sample based on the well known PetClinic web application: you can find it here.

Any feedback is highly appreciated: feel free to comment on this post, or to ask a question through the Spring Modules forum.

Have fun!

Thursday, October 05, 2006

Spring 2.0 and Maven 2

And finally, the happy ending: Spring 2.0 is in the Maven 2 repository!

This is a great gift for the whole (rich) Maven 2 community.

My best congratulations to Ben Hale and the whole Spring team!

Wednesday, October 04, 2006

Great news about Spring

Hi all,

there are great news in the air about the Spring Framework.

I think all of you know that the final 2.0 version has been released yesterday, but you may not know that Spring 2.0 will be published into the official Maven2 repository in the next days: take a look here.
That's great!

In the meantime, Spring Modules 0.6 has been also published yesterday into Maven2 repository: that's great, too!

Stay tuned!

Wednesday, September 06, 2006

I'm back

Hello guys,

I'm finally back.

I've been very busy at work.
Then, I've been on vacations for three weeks.

Now?

Well ... what a question ... I'm busy, busy, busy!

I have, as usual, a lot of work, and I'm applying myself in fixing the last issues prior to the upcoming Spring Modules release.

However, I'll try to blog as much as possible, obviously trying to write something interesting ... at least by my point of view!

So stay tuned.

Cheers!

Friday, July 21, 2006

Constructing View objects with the Builder pattern

Domain-Driven Design gives us important concepts like Entities, Value objects, Factories, Repositories, Aggregates, Services, but doesn't talk about View objects and how to construct them.

View objects, as I see them, are a kind of DTOs without the burden of DTOs.
While DTOs represent and duplicate domain objects data, View objects simply represent data requested by a view and extracted from one or more domain objects.
What's more important, they cannot be used as replacements of domain objects, because they are immutable containers of simple data.
So, their use is (and must be) restricted to those scenarios where you need read only report-style views and fast performances.

What about View objects construction?

Like discussed in this post from the Domain-Driven Design group, there are different possibilities.
I think the best one is to use the Builder pattern:

Separate the construction of a complex object from its representation so that the same construction process can create different representations.

You can use the Builder pattern for implementing build methods that directly access the data store for constructing different parts of the View object.
This gives you the following advantages:

  • You can separate the process of building your View object in different steps, and use only the steps you need for a particular view page, without even having to construct the full View object.

  • You can have a generic ObjectAViewBuilder with generic buildPartA() and buildPartB() steps, and then having subclasses specify what data you actually need for every given step, i.e. depending on a particular view page.



This gives you better performances and higher flexibility.

Let us go now with a simple example.

Say we have two domain objects: Employee and Office (I'm not going to show interfaces here because they are of no interest in our context).


@Entity()
@Table(name="Employee")
@Proxy(proxyClass=Employee.class)
public class EmployeeImpl implements Employee {

@Id()
private int id;
@Version()
private int version;

@Column(unique=true)
private String matriculationCode;
private String firstname;
private String surname;
@ManyToOne(targetEntity=OfficeImpl.class)
private Office office;

protected EmployeeImpl() {}

public EmployeeImpl(String matriculationCode) {
this.matriculationCode = matriculationCode;
}

public String getFirstname() {
return firstname;
}

public void setFirstname(String firstname) {
this.firstname = firstname;
}

public String getSurname() {
return surname;
}

public void setSurname(String surname) {
this.surname = surname;
}

public String getMatriculationCode() {
return matriculationCode;
}

public Office getOffice() {
return this.office;
}

public void setOffice(Office office) {
this.office = office;
}

public boolean equals(Object obj) {
if (obj == null || !(obj instanceof Employee)) return false;

Employee other = (Employee) obj;

return new EqualsBuilder().append(this.getMatriculationCode(), other.getMatriculationCode()).isEquals();
}

public int hashCode() {
return new HashCodeBuilder().append(this.getMatriculationCode()).toHashCode();
}
}


@Entity()
@Table(name="Office")
@Proxy(proxyClass=Office.class)
public class OfficeImpl implements Office {

@Id()
private int id;
@Version()
private int version;

@Column(unique=true)
private String officeId;
private String name;

protected OfficeImpl() {}

public OfficeImpl(String officeId, String name) {
this.officeId = officeId;
this.name = name;
}

public String getName() {
return name;
}

public String getOfficeId() {
return officeId;
}

public boolean equals(Object obj) {
if (obj == null || !(obj instanceof Office)) return false;

Office other = (Office) obj;

return new EqualsBuilder().append(this.getOfficeId(), other.getOfficeId()).isEquals();
}

public int hashCode() {
return new HashCodeBuilder().append(this.getOfficeId()).toHashCode();
}
}


The two domain entities are annotated with EJB3 annotations, so they are persistent objects.

Now, your application needs some report-style view listing a few employees data, but you don't want to get the full Employee object graph: so you create a marker EmployeeView interface for representing employee related views, and an extended interface for showing just some simple data from an employee and its related office, the SimpleEmployeeView (with related implementation):


public interface EmployeeView extends Serializable {
}


public interface SimpleEmployeeView extends EmployeeView {

public String getMatriculationCode();

public String getFirstname();

public String getSurname();

public String getOfficeName();
}


public class SimpleEmployeeViewImpl implements SimpleEmployeeView {

private String matriculationCode;
private String firstname;
private String surname;
private String officeName;

public String getMatriculationCode() {
return matriculationCode;
}

public void setMatriculationCode(String matriculationCode) {
this.matriculationCode = matriculationCode;
}

public String getFirstname() {
return firstname;
}

public void setFirstname(String firstname) {
this.firstname = firstname;
}

public String getSurname() {
return surname;
}

public void setSurname(String surname) {
this.surname = surname;
}

public String getOfficeName() {
return officeName;
}

public void setOfficeName(String officeName) {
this.officeName = officeName;
}
}


Please note: the view implementation has setters method, while the interface has not. This is because the view (hence its interface) has to be immutable, but setter methods must be used by the builder for constructing the View object.

Once you have some View object, you need a Builder!
So here is the generic Builder interface for constructing generic EmployeeView objects (EmployeeViewBuilder), and its concrete implementation (SimpleEmployeeViewBuilder):


public interface EmployeeViewBuilder {

public void buildEmployee(String matriculationCode);

public void buildEmployeeOffice();

public EmployeeView getEmployeeView();
}


public class SimpleEmployeeViewBuilder implements EmployeeViewBuilder {

private HibernateTemplate hibernateTemplate;
private SimpleEmployeeViewImpl view = new SimpleEmployeeViewImpl();

public void buildEmployee(String matriculationCode) {
List<Object[]> result = hibernateTemplate.find("select e.matriculationCode, e.firstname, e.surname from com.blogspot.sbtourist.domain.EmployeeImpl e where e.matriculationCode = ?", matriculationCode);
for (Object[] values : result) {
view.setMatriculationCode((String) values[0]);
view.setFirstname((String) values[1]);
view.setSurname((String) values[2]);
}
}

public void buildEmployeeOffice() {
if (view.getMatriculationCode() == null) {
throw new IllegalStateException("First call buildEmployee() method!");
}
List<String> result = hibernateTemplate.find("select e.office.name from com.blogspot.sbtourist.domain.EmployeeImpl e where e.matriculationCode = ?", view.getMatriculationCode());
for (String value : result) {
view.setOfficeName(value);
}
}

public SimpleEmployeeView getEmployeeView() {
return this.view;
}

public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}

public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
}



As you can see, SimpleEmployeeViewBuilder builds each part of the View object directly using data access API (in our example, Hibernate API), retrieving only the data it needs.
And, if you have a different employee view page, just implement a different EmployeeView with related EmployeeViewBuilder!

Finally, your Builder objects will have to be used in the Service layer, into view specific methods:


public EmployeeView getEmployeeWithOfficeView(String employeeMatriculationCode) {
EmployeeViewBuilder builder = new SimpleEmployeeViewBuilder();
builder.buildEmployee(employeeMatriculationCode);
builder.buildEmployeeOffice();
return builder.getEmployeeView();
}



I'd like to know your opinion, every feedback is welcome.

Happy building!

Updates
07/25/2006 : Improved example code (thanks to Christofer Jennings).

Friday, July 14, 2006

Spring Modules 0.5 and the XT Framework

Today, Spring Modules 0.5 has been released.

It contains a lot of improvements, as you can read from the announcement, among which you can find my main contribution to the project: the brand new Spring Modules XT Framework.

Born toward the end of the last year as SpringXT, you can find its old (never publicly announced) home page here, I'm proud and happy to say it is now a top level module of Spring Modules!

What is it?

Spring Modules XT, strongly influenced by modern Domain-Driven Design techniques and Ajax technologies, has a main aim: let you develop simple-to-complex business applications with your domain model in mind, and let you easily and powerfully construct the presentation layer of your domain model thanks to Spring MVC and Ajax techniques.
So, it provides an XT Modeling Framework, implementing Domain-Driven Design and AOP based techniques for enhancing your domain model, and XT Ajax Framework, an Ajax implemention which doesn't require you to learn any other framework or deeply change your application, because completely built on (and thought for) Spring MVC.

I invite you to take a look at its documentation and play with it.
It is just at its first stable release and it needs a lot of feedback!

Above all that, give the whole Spring Modules project a look, pick the module you need ... and let us know through its forum and mailing lists!

Tuesday, July 11, 2006

Avoid your getters and setters, Part 1

In the Java world, getters and setters are one of those things everyone says to hate but everyone actually uses.
I think this is mainly because:

  1. They are procedural, heritage of C-style (or even older) programming.

  2. They are a practice embedded by JavaBeans conventions.

  3. Many ORM and Web frameworks heavily use getters and setters.


In a series of blog posts called Avoid your getters and setters, I'll try to show you some ideas for avoiding getters and setters, by simply applying some fundamental Object Oriented and Domain Driven Design principles.

Any feedback will be highly appreciated.

Let's go!

Avoid your getters and setters: Programming to an Interface

From the GOF book:

Don't declare variables to be instances of particular concrete classes. Instead, commit only to an interface
defined by an abstract class.

This is probably the main Object Oriented principle: we could write words and words about it, but I prefer to remind you some good books like the one cited above, or like this one.

Programming to an interface is the first step toward good OO code.
Moreover, and here we come to our point, if you program to an interface, and think in terms of interfaces, you can better choose the getters and setters you need, while removing or hiding the unwanted ones.

First, thinking in terms of interfaces is thinking in terms of contracts.
Say you have a Customer entity in your domain model.
How does it interact with other entities?
What are its behaviours?
What its pre / post conditions and invariants?
That is: what is the contract defined by the Customer interface?

You may have an issue(Order ) method, and you may discover you need to know, for business reasons, the customer code.
So, here is our Customer interface:


public interface Customer {

public String getCustomerCode();

public void issue(Order newOrder);
}


Think always in terms of business contracts: all methods in your interfaces must have a business meaning.
Obviously, also getters and setters can have business meaning, which is the case of getCustomerCode().
All getters and setters without this meaning must be removed from the interface.

Here it comes your preferred ORM tool or Web Framework: it requires a lot of setters and getters for writing and reading properties, and you really don't want to do all that dirty job by hand!

What to do?

Too bad, we cannot actually avoid all those getters and setters, but we can hide them from your code simply declaring them in your concrete classes, and leaving them out from interfaces: your code, depending on interfaces, will never see all those unwanted methods!.

So you have a Customer concrete class:


public class CustomerImpl implements Customer{

...

public String getCustomerCode() { ... }

public void issue(Order newOrder) { ... }

// Setters and getters not in the interface:

public void setSurname(String surname) { ... }

public String getSurname() { ... }
}


What really hurts is the setSurname() method: in your business, once defined a customer's surname should never change!
But, hey: your code is written in terms of the Customer interface, so it will not be able to call unwanted methods!


public class CustomerService {

public void register(Customer c) { ... }
}


public class CustomerDAO {

public void save(Customer c) { ... }
}


Moreover, under the hood they actually are CustomerImpl objects, so your Web or ORM frameworks will be able to call all getters and setters thanks to Java reflection!



That's all.
And it's awful simple.
I hope to have explained well how you can hide getters and setters by simply programming to interfaces, while still using common frameworks.

In my next Avoid your getters and setters post we'll talk about the expert pattern ... in the meantime, let me know what do you think!

Saturday, July 08, 2006

Java should provide interface level equality

While working to a business domain model in a pure Object Oriented approach, one thing I miss in Java is the concept, hence the implementation, of type equality, where for type I mean interface.

Let me explain with a simple example.

Say you have a Customer entity, that in your domain model is an interface, that is, a type:


public interface Customer {

public String getCustomerCode();

public String getSurname();

public Date getBirthdate();
}



You have different concrete Customer implementations, i.e. StandardCustomer and PremiumCustomer, but customer equality is the same for all customers, because defined by the customer code: so, you want to define equality for the Customer type.
Too bad, in Java the only way to go is to implement a base class for all customers, defining, among other methods, the equals() one:


public abstract class BaseCustomer implements Customer {

public String getCustomerCode() { ... }

public String getSurname() { ... }

public Date getBirthdate() { ... }

public boolean equals(Object obj) {
if ((obj == null) || (!(obj instanceof Customer))) return false;

Customer other = (Customer) obj;

return this.getCustomerCode().equals(other.getCustomerCode());
}
}


public class StandardCustomer extends BaseCustomer {
...
}


public class PremiumCustomer extends BaseCustomer {
...
}



However, this is not correct, nor safe, because you could implement another Customer directly implementing the interface, or even extending another base class: doing so, you would break the equals contract.
For example:


public class CustomerOfTheMonth implements Customer {

public String getCustomerCode() { ... }

public String getSurname() { ... }

public Date getBirthdate() { ... }

// You forget to implement equals(), or maybe implement a different one ....
}



Now, a StandardCustomer is equal to a CustomerOfTheMonth, but a CustomerOfTheMonth is not equal to a StandardCustomer!
This is because BaseCustomer defines equality for all Customers, but CustomerOfTheMonth, while being a Customer, is not a base one!
So, the symmetry of the equals() method is broken!

The problem would be solved if we could implement the equals() method into the Customer interface, rather than into the BaseCustomer concrete class: if you had then to implement equality in a different way for some concrete class, you'd be also free to overwrite it later!

Here we come back to the beginning of my post: why doesn't Java provide interface level equality?

Tuesday, July 04, 2006

A great day

About one month has passed since the last time I've made a post.
I'm very busy at the moment, but today is a great day.

I'd like to say I'm very proud of being, from now on, a Spring Modules committer!



Thank you very much to Costin Leau, the Spring Modules Lead, and the whole team: I'll try to do my best!

What will be my involvement in Spring Modules?

Stay tuned, I'll let you know in another post.

Sunday, June 11, 2006

Solving Method Contract Problems

In these last days an interesting discussion about the final Java keyword took place in many sites and blogs: take a look here and here.

I don't want to add my opinion about that because everything has been already discussed.
What caught my attention was the following statement in this very interesting blog post by Elliotte Rusty Harold:


It is a general principle of object oriented programming that an instance of the subclass can be used anywhere an instance of the superclass is expected. This is the very
definition of polymorphism. This means that the subclasses must maintain the class invariants and postconditions of their superclasses because client code might be depending
on those invariants and postconditions. Failure to do so is a contract violation. For example, if a Clock class promises that the getHours() method always returns a value
between 1 and 12, then this must still be true for a MilitaryClock subclass’s getHours() method. The MilitaryClock subclass can add a different getMilitaryHours() method that
returns a value between 0 and 23. However it must not violate the rule that getHours() always returns a number between 1 and 12.


I'm a huge fan of Design By Contract principles and agree with Elliotte in many points.
However, what I disagree with is how he solves the problem of maintaining the correct post-conditions on the getHours() method of Clock, that is, adding a getMilitaryHours() to MilitaryClock.

Why do I disagree?

Say you have a Display object for displaying time information through a Clock object, thanks to a displayTime(Clock c) method.
If Display.displayTime(Clock c) calls c.getHours() for obtaining the right hour time, it will not work with a 24 hours based MilitaryClock, because it will always display a 12 hours based Clock even if the actual Clock instance is a MilitaryClock!
Following Elliotte solution, Display should call getMilitaryHours(), but how?
Display doesn't know the actual type of Clock!
Moreover, adding a getMilitaryHours() method doesn't stop the client to use the standard getHours() method! Is this correct? Does the 12 hours based method make some sense for a MilitaryClock?

So, I see two solutions.

The first one: designing a Clock interface and two concrete implementations: StandardClock and MilitaryClock.
The Clock interface will have a getHours() method documenting the weaker applicable post-conditions, that is, an hour value between 0 and 23.
The StandardClock will strengthen the post-condition, outputting only values between 0 and 12.
The MilitaryClock will leave the post-condition as is.
This is safe and doesn't break any contract.
Elliotte could answer that interfaces are bad because don't let you verify conditions, forcing you to simply document them, and implementors to read your documentation.
I should write a whole blog post about this, but for now let me simply say that the value of interfaces is worth the price to pay. Surely.

The second solution: suppressing the getHours() method and implement a Clock.display() method, assigning to clock the responsability of displaying itself whatever time format it use, and let Display.displayTime(Clock c) call c.display().

Maybe Elliotte example was oversimplified, or his solution referred to a situation where you cannot change the base class (Clock), but simply saying that the solution to a "contract conditions problem" is adding another method, is IMHO a bit misleading.

My two euro cents.

What's your opinion about this?