September 27, 2009

State pattern: introducing domain-driven design

Some domain objects in many enterprises applications include a concept of state. State has two main characteristics: the behavior of domain object (how it responds to business methods) depends on the state and business methods may change the state forcing the object to behave differently after being invoked.

If you can’t image any real-life example of domain objects’ state, think of a Car entity in rental company. The Car, while remaining the same object, has additional flag called status, which is crucial for the company. The flag may have three values: AVAILABLE, RENTED and MISSING. It is obvious that the Car in RENTED or MISSING state cannot be rented at the moment and rent() method should fail. But when the car is back and its status is AVAILABLE, calling rent() on Car instance should clearly, apart from remembering customer who rented the car, changing the car status to RENTED. The status flag (probably single character or int in your database) is an example of objects’ state, as it influences the business methods and vice-versa, business methods can change it.

Now think for a while, how would you implement this scenario which, I am sure, you have seen many times at work. You have many business methods depending on current state and probably many states. If you love object oriented programming, you might immediately thought about inheritance and creating AvailableCar, RentedCar and MissingCar extending Car. It looks good, but is very impractical, especially when Car is persistent object. And actually this approach is not well designed: it is not the whole object that changes, but only a piece of its internal state – we are not replacing object, only changing it. Maybe you thought about cascade of if-else-if-else... in each method performing different task depending on state. Don’t go there, believe me, it is the path to the Code Maintenance Hell.

But we are going to use inheritance and polymorphism though, but in more clever way: using State GoF pattern. As an example I have chosen Reservation entity which can have following statuses:




Flow is simple – when the reservation is created, it has NEW status (state). Then some authorized person can accept the reservation, causing (let’s say) seat to be temporarily reserved and sending user an e-mail asking to pay for the reservation. Then, when user performs money transfer, money is accounted, ticket printed and second e-mail sent to the client. Of course you are aware that some actions have dramatically different side-effects depending on Reservation current status. For example you can cancel reservation at any time, but depending on Reservation status this may result in transferring money back and cancelling reservation or only in sending user an e-mail. Also some actions have no sense in particular statuses (what if user transferred money to already-cancelled reservation?) or should be ignored. Now image how hard it would be to write each business method exposed on state machine diagram above, if you had to use if-else construct for every status and every method...

Unlike my previous posts I will not explain original GoF State design pattern. Instead I will introduce my little variation over this pattern using Java 5 enum capabilities. In lieu of creating abstract class/interface for state abstraction and writing implementation for each state, I have simply created enum containing all available states/statuses:


public enum ReservationStatus {
NEW,
ACCEPTED,
PAID,
CANCELLED;
}


Also I created interface for all business methods depending on status, which seems to be a good idea. Treat this interface as abstract base for all states, but we are going to use it in a bit different way:

public interface ReservationStatusOperations {
ReservationStatus accept(Reservation reservation);
ReservationStatus charge(Reservation reservation);
ReservationStatus cancel(Reservation reservation);
}


And finally Reservation domain object, which happens to be JPA entity (getters/setters omitted, or maybe we can just use Groovy and forget about them?):

public class Reservation {
private int id;
private String name;
private Calendar date;
private BigDecimal price;
private ReservationStatus status = ReservationStatus.NEW;

//getters/setters

}




If Reservation is persistent domain object, its status (ReservationStatus) should obviously be persistent as well. This observation brings us to the first big advantage of using enum instead of abstract class: JPA/Hibernate can easily serialize and persist Java enum in database using enum’s name or ordinal value (by default). In original GoF pattern we would rather put ReservationStatusOperations direcly in domain object and switch implementations when status changes. I suggest to use enum and only change enum value. Another (less framework-centric and more important) advantage of using enum is that all possible states are listed in one place. You don’t have to crawl your source code in search for all implementations of base State class – everything can be seen in one, comma-separated list.

OK, take a deep breath, now I will explain how all the pieces work together and why, on earth, business operations in ReservationStatusOperations return ReservationStatus. First, you must recall what actually enum’s are. They are not just a collection of constants in single namespace like in C/C++. In Java, enum is rather a closed set of classes that inherit from common base class (e.g. ReservationStatus), which in turns inherits from Enum. So while using enums, we might take advantage of polymorphism and inheritance:

public enum ReservationStatus implements ReservationStatusOperations {

NEW {
public ReservationStatus accept(Reservation reservation) {
//..
}

public ReservationStatus charge(Reservation reservation) {
//..
}

public ReservationStatus cancel(Reservation reservation) {
//..
}
},

ACCEPTED {
public ReservationStatus accept(Reservation reservation) {
//..
}

public ReservationStatus charge(Reservation reservation) {
//..
}

public ReservationStatus cancel(Reservation reservation) {
//..
}
},

PAID {/*...*/},

CANCELLED {/*...*/};
}


Although it’s tempting to write ReservationStatusOperations in such a manner, it’s a bad idea for a long term development. Not only the enum source code would be extensively long (total number of implemented methods would be equal to a number of statuses multiplied by number of business methods), but also badly designed (business logic for all states in single class). Also, enum implementing interface and rest of this fancy syntax may be counterintuitive for anyone who didn’t passed SCJP exam in last 2 weeks. Instead, we will provide some simple level of indirection, because "Any problem in computer science can be solved with another layer of indirection" [*]:

public enum ReservationStatus implements ReservationStatusOperations {

NEW(new NewRso()),
ACCEPTED(new AcceptedRso()),
PAID(new PaidRso()),
CANCELLED(new CancelledRso());

private final ReservationStatusOperations operations;

ReservationStatus(ReservationStatusOperations operations) {
this.operations = operations;
}

@Override
public ReservationStatus accept(Reservation reservation) {
return operations.accept(reservation);
}

@Override
public ReservationStatus charge(Reservation reservation) {
return operations.charge(reservation);
}

@Override
public ReservationStatus cancel(Reservation reservation) {
return operations.cancel(reservation);
}
}


This is the final source code for our ReservationStatus enum (implementing ReservationStatusOperations is not necessary). To put things simple: each enum value has its own distinct implementation of ReservationStatusOperations (Rso for short); this implementation is passed as a constructor argument and assigned to final field operations. Now, whenever business method is called on enum, it will be delegated to ReservationStatusOperations implementation dedicated to this enum:

ReservationStatus.NEW.accept(reservation);        //will call NewRso.accept()
ReservationStatus.ACCEPTED.accept(reservation); //will call AcceptedRso.accept()


The last piece of the puzzle is Reservation domain object including business methods:

public void accept() {
setStatus(status.accept(this));
}

public void charge() {
setStatus(status.charge(this));
}

public void cancel() {
setStatus(status.cancel(this));
}

public void setStatus(ReservationStatus status) {
if (status != null && status != this.status) {
log.debug("Reservation#" + id + ": changing status from " + this.status + " to " + status);
this.status = status;
}


What happens here? When you call any business method on Reservation domain object instance, corresponding method is being called on ReservationStatus enum value. Depending on current status, different method (of different ReservationStatusOperations implementation) will be called. But there is no switch-case or if-else construct, only pure polymorphism. For example if you call charge() when status field points to ReservationStatus.ACCEPTED, AcceptedRso.charge() is being called, the customer who made the reservation will be charged and reservation status changes to PAID. But what happens if we call charge() again on the same instance? status field now points to ReservationStatus.PAID, so PaidRso.charge() will be executed, which throws exception (charging already paid reservation is invalid). With no conditional code, we implemented state-aware domain object with business methods included in the object itself.

One thing I haven’t mentioned yet is how to change the status from business method. This is the second difference from original GoF pattern. Instead of passing StateContext instance to each state-aware operation (like accept() or charge()), which can be used to change the status, I simply return new status from business method. If the status is not null and different from the previous one (setStatus() method), reservation transits to a given status. Let’s take a look at how it works on AcceptedRso object (its methods are being executed when Reservation is in ReservationStatus.ACCEPTED status):

public class AcceptedRso implements ReservationStatusOperations {

@Override
public ReservationStatus accept(Reservation reservation) {
throw new UnsupportedStatusTransitionException("accept", ReservationStatus.ACCEPTED);
}

@Override
public ReservationStatus charge(Reservation reservation) {
//charge client's credit card
//send e-mail
//print ticket
return ReservationStatus.PAID;
}

@Override
public ReservationStatus cancel(Reservation reservation) {
//send cancellation e-mail
return ReservationStatus.CANCELLED;
}

}


Behavior of Reservation in ACCEPTED status can be easily followed by reading class above: accepting for the second time (reservation is already accepted) will throw an exception, charging will charge client’s credit card, print him a ticket and send e-mail etc. Also, charging returns PAID status, which will cause the Reservation to transit to this state. This means another call to charge() will be handled by different ReservationStatusOperations implementation (PaidRso) with no conditional code.

This would be all about the State pattern. If you are not convinced to this design pattern, compare the amount of work and how error-prone it is with classic approach using conditional code. Also think for a while what is needed when adding new state or state-dependent operation and how easy it is to read such a code.

I didn’t show all ReservationStatusOperations implementations, but if you would like to introduce this approach in your Spring or EJB based JEE application, you have probably saw a big lie out there. I gave comments on what should happen in each business methods, but not provided actual implementations. I didn’t, because I would come across big problem: Reservation instance is created by hand (using new) or by persistence framework like Hibernate. It uses statically created enum which creates manually ReservationStatusOperations implementations. There is no way to inject any dependencies, DAOs and services, to this classes, as their lifecycle is controlled out of the Spring or EJB container scope. Actually, there is a simple yet powerful solution, using Spring and AspectJ. But be patient, I will explain it in details in the next post soon, adding some domain-driven flavor to our application.

September 20, 2009

Spring AOP riddle demystified

In one of my previous posts I gave you an example of some unexpected behavior when using Spring AOP proxies. Few days later I began to read "Pro Spring 2.5" by Jan Machacek, Jessica Ditt, Aleksa Vukotic and Anirvan Chakraborty. It turned out that my riddle is actually a well known problem which has more than one solution. Also one of my Readers suggested some different approach.

This almost nine-hundred-pages book has a whole section in Chapter 6: Advanced AOP introducing the problem which I believed I have discovered. There is even a programmatic solution, similar to EJB’s SessionContext.getBusinessObject(). But if the EJB method may be treated as somewhat standardized, using AopContext.currentProxy() looks awkward and unnecessarily couples you to the Spring framework. I almost feel guilty for telling you about this method and you should feel the same if you thought about using it. Luckily, authors of "Pro Spring 2.5" also discourage its use.

So if you want to have in-depth understanding of Spring AOP, I suggests you to take I look at this book. Or at least follow my blog, as I will surely present a few more concepts considering Spring AOP and AspectJ in the future. Stay tuned!

September 16, 2009

Adapter pattern: accesing Ehcache via Map interface

Suppose you have some client code (developed by you, legacy code or third-party library) which requires object of some specific type. On the other hand you already have almost exactly the same object, which does almost the same (in other words, fulfils similar contract). But the problem is, although both, required and yours, objects are pretty much the same, they have slightly or completely different interfaces. And in strongly typed Java world, even slightly means incompatible.

If you travel a lot, you probably came across the same problem in your real life. European and American AC power plugs and sockets are different. Although they both have same purpose – provide you with electrical power – and have similar contract (voltage, frequency, etc.), they simply don’t fit each other. Even though they are semantically equivalent, they are syntactically incompatible (have different shapes). The solution is the same for both developer and traveler: provide an adapter, which will have two interfaces: one fitting client (either Java code or your laptop power supplier) and one wrapping and translating target (your Java object or power socket found in local hotel).

OK, let’s go back to programming. As an example I have chosen Ehcache library, which is amazingly useful caching facility, mostly known as being Hibernate’s second level cache provider. But actually, Ehcache can be used in a variety of places, from a simple HashMap replacement to distributed, shared memory store with automatic peer discovery and disk persistence. If you have written some home-made caching solution and integrated it with your application, Ehcache should have been your first choice.

And here our problem arises. Look carefully at Map and Ehcache interfaces. They look similar, aren’t they? Both Map and Ehcache are data structures used to store data in key-value (dictionary) manner. It is tempting to use full-featured Ehcache instead of simple map and take advantage of automatic expiration, eviction and size/memory constraints. But since Ehcache interface does not extend Map, there is no direct way to achieve this. Of course, you may rewrite the code to use Ehcache instead of simple map, but in many cases it is impossible or too expensive (like your boss says, nothing’s impossible, only unprofitable). So you ask yourself, since the code requires me to supply any implementation of Map interface, maybe I can fool it and write special implementation, that only delegates to hidden Ehcache instance? In other words, this implementation won’t do almost anything by itself, instead only proxying and translating every call to Map methods to corresponding similar Ehcache operations. Yes, we are going to write implementation of Adapter pattern.




Figure above illustrates the design of our Ehcache adapter: it implements interface required by client code (Map), wrapping and hiding the target interface (Ehcache; sometimes called Adaptee). In Java we start by something like this:

public class EhcacheMapAdapter<K, V> implements Map<K, V> {
private final Ehcache targetCache;
//...
}


The most important part is to implement Map interface in the way that does not violate the map contract. More generally speaking, Adapter must delegate to target in such way, that it behaves exactly the same as the client interface specifies – and same as any other implementation. In other words – if you have good unit tests for particular Map implementation, they should pass as well for the adapter. Here is the full source code:

public class EhcacheMapAdapter<K, V> implements Map<K, V> {

private final Ehcache targetCache;

public EhcacheMapAdapter(Ehcache targetCache) {
this.targetCache = targetCache;
}

@Override
public int size() {
return targetCache.getSize();
}

@Override
public boolean isEmpty() {
return size() == 0;
}

@Override
public boolean containsKey(Object key) {
return targetCache.get(key) != null;
}

@Override
public boolean containsValue(Object value) {
for (Object key : targetCache.getKeys()) {
Element element = targetCache.get(key);
if (element != null && element.getValue() != null && element.getValue().equals(value))
return true;
}
return false;
}

@Override
public V get(Object key) {
Element element = targetCache.get(key);
if (element != null)
return (V) element.getValue();
else
return null;
}

@Override
public V put(K key, V value) {
V previousValue = get(key);
targetCache.put(new Element(key, value));
return previousValue;
}

@Override
public V remove(Object key) {
V previousValue = get(key);
targetCache.remove(key);
return previousValue;
}

@Override
public void putAll(Map<? extends K, ? extends V> m) {
for (Map.Entry<? extends K, ? extends V> entry : m.entrySet())
put(entry.getKey(), entry.getValue());
}

@Override
public void clear() {
targetCache.removeAll();
}

@Override
public Set<K> keySet() {
return new HashSet<K>(targetCache.getKeys());
}

@Override
public Collection<V> values() {
final ArrayList<V> values = new ArrayList<V>();
for (Object key : targetCache.getKeys()) {
Element element = targetCache.get(key);
if (element != null)
values.add((V) element.getValue());
}
return values;
}

@Override
public Set<Entry<K, V>> entrySet() {
final Set<Entry<K, V>> values = new HashSet<Entry<K, V>>();
for (Object key : targetCache.getKeys()) {
Element element = targetCache.get(key);
if (element != null)
values.add(new EhcacheEntry<K, V>((K)key));
}
return values;
}

private class EhcacheEntry<K, V> implements Entry<K, V> {

private final K key;

public EhcacheEntry(K key) {
this.key = key;
}

@Override
public K getKey() {
return key;
}

@Override
public V getValue() {
Element element = targetCache.get(key);
return element != null? (V) element.getValue() : null;
}

@Override
public V setValue(V value) {
Element element = targetCache.get(key);
V previousValue = element != null? (V) element.getValue() : null;
targetCache.put(new Element(key, value));
return previousValue;
}
}
}


Look carefully at any method – they mostly delegate to adaptee, but sometimes you must code a little bit to achieve equivalent functionality. I wrote a very small unit test to check that adapter implementation follows the map contract, though in order to be 100% sure, we should write at least couple test for every method independently. Please note that the test is written in Groovy and uses Groovy syntax – this shows that adapter can be safely used in any code which expects Map.

public class EhcacheMapAdapterTest extends GroovyTestCase {

public void testEhcacheMapAdapter() {
//given
Ehcache cache = CacheManager.getInstance().getCache("test");
def map = new EhcacheMapAdapter<String, Integer>(cache);

//when
map.one = 1
map['two'] = 2
map.put('thirty four', 34)

//then
assertEquals 3, map.size()
assertTrue map.containsKey('one')
assertTrue map.containsKey('two')
assertFalse map.containsKey('three')
assertTrue map.containsKey('thirty four')

assertEquals 2, map.get('two')
assertTrue map.containsValue(1)
}

}


Final notes: our implementation has some additional benefit over using Ehcache directly: it is not only simpler, but also introduces strong-typing (Ehcache keys and values are of Object type). But to be precise, our adapter does not exactly conform to Map contract. It might happen, that value once put in map will not be present later even if it was not manipulated in the meantime. This is because the element might have expired and been removed from cache.

I hope you all get the idea of Adapter pattern. Maybe some of you have been using this pattern not knowing about that. For example I have been working with IBM WebSphere MQ message broker, which is available for Java developer via JMS adapter. I could use message driven beans, Spring’s JmsTemplate etc. just because MQ did provide their implementation of ConnectionFactory and queues. It was much easier to integrate it in existing app, rather than using vendor specific API. Think of Adapters before you rewrite legacy code or look for existing ones (like JDBC from MS Excel bridges).

September 3, 2009

Injecting methods at runtime to Java class in Groovy

I recently finished reading "Programming Groovy: Dynamic Productivity for the Java Developer" and this book really opened my eyes on what Groovy language really is. Most tutorials or lectures I have attended are focused on syntactical sugar: closures, operator overloading, easier access to bean properties or maps. Elvis operator, spread operator, spaceship operator...

But the strength of Groovy is not syntactic sugar on a Java cake. Groovy is a brand new dish with really exotic taste, which not everybody would enjoy. The gap between Java and Groovy is really huge, although they integrate tightly and seamlessly. But remember, Firefox did not became so popular because it was so similar to IE, but because it was different [1]. Maybe Groovy is not better than Java, but is certainly worth trying. Thanks to "Programming Groovy..." I realized what amazing things can be done using Groovy which you would never even thought about in Java.

As Chinese said, Java code is worth more than a thousand words (or something like that...), I’ll give you some short example announced in post title. Suppose you have some POJO:

public class Person {
private String name;
private Calendar dateOfBirth;
private BigDecimal salary;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Calendar getDateOfBirth() {
return dateOfBirth;
}

public void setDateOfBirth(Calendar dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}

public BigDecimal getSalary() {
return salary;
}

public void setSalary(BigDecimal salary) {
this.salary = salary;
}
}


Yes, this is Java class, remember that. Our task is to create simple validator, which will check whether all properties are not-null of a particular Java Bean instance (e.g Person). If any null field found, exception should be thrown.

Doing this in the classic way, you would write some sort of utility class with method like:

public static void validate(Object pojo) throws IllegalStateException {/*...*/}


This approach is so obvious, that I won’t even explain this API. Behind the scenes some nasty reflection with tons of exception handling and method name parsing code will be used to make the method generic. If you are clever, you would use Commons-BeanUtils. But this is still poor object-oriented design, as data (properties of a JavaBean) and operations (validate() method operating on data) are separated. Wouldn’t it be great to have validate() method in Person and every other bean you wish? To achieve this, you would probably think about inheritance and placing validate() in some abstract base class of all your Java Beans.

No, stop that! This is still bad design, although much more subtle. Inheritance represents is-a relationship. If you want to use the same operation in many objects, you should rather use delegation. See "Replace Inheritance with Delegation" chapter in Fowler’s "Refactoring: improving the design of existing code" (I know, I know, some parts of the book are not so outdated :-)). But if you are not so sensitive about code design (why?!?), there is another problem – this approach cannot be applied to third-party classes, which you are not allowed to change.

This is the place where Groovy comes in with its amazing dynamic capabilities. First I will prepare some Groovy test case, which will explain what I am trying to achieve. Test-driven development, anybody?

public class PersonTest extends GroovyTestCase {

void testAllPropertiesNullShouldThrow() {
def person = new Person();
shouldFail(IllegalStateException) {person.validate()}
}

void testSingleNullPropertyShouldThrow() {
def person = new Person(name: "John Smith", salary: 1234d)
shouldFail(IllegalStateException) {person.validate()}
}

void testAllPropertiesSetShouldNotThrow() {
def person = new Person(name: "John Smith", dateOfBirth: Calendar.instance, salary: 1234d)
person.validate()
}

}


Read those tests carefully. Not because I use elegant shouldFail() template nor very concise way of initializing POJO (even though it does not have any non-default constructor!) The most surprising fact is that I run validate() method on Person class instance and the code compiles just fine! It doesn’t matter this method does not exist on compile time, even if it is Java object. Groovy’s dynamic. But what happen if I run this test?

groovy.lang.MissingMethodException: No signature of method: Person.validate() is applicable for argument types: () values: []
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:54)
at org.codehaus.groovy.runtime.callsite.PojoMetaClassSite.call(PojoMetaClassSite.java:46)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:40)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:117)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:121)
at PersonTest.testAllPropertiesSetShouldNotThrow(PersonTest.groovy:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:40)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:90)


Surely, Person Java class does not have validate() method, even if Groovy compiler assumed differently. So you might ask yourself, what is the purpose of such a weak compilation? Well, now comes the best part:

void setUp() {
Person.metaClass.validate = {->
delegate.properties.each {property, value ->
if (value == null)
throw new java.lang.IllegalStateException("Property $property is null")
}
}
}


What I’ve done here is I injected method called validate() to meta class of Person Java class at runtime. Since now, every instance of Person class is capable of handling validate() method even though this method has not been known during compilation. Quick test case execution and... success, not only the method is known, but it works as expected.

I won’t discuss details of validate() implementation, simply try to rewrite it in Java, you’ll see the difference. But it is not the point! I created brand new method and applied it to arbitrary Java class (of course, if Person was Groovy class, it would work as well). This is absolutely impossible in static Java. And if I add that by implementing methodMissing() object could handle ANY nonexistent method call...

You might ask yourself once again, what is the purpose of such a dangerous and unpredictable toy? Well, I am about to obtain "The Definitive Guide to Grails"*, which also explains GORM framework. If you would like to make Person class persistent, Groovy ORM will automatically inject save() method to Person class, so you could write:

new Person(name: "John Smith").save()


No DAO, no session, na EntityManager. But you could also write:

def list = Person.findByNameLikeAndSalaryGreaterThan("John%", 1000)


Where is the implementation of this not-so-simple method? You don’t have to implement it, Groovy will! It will discover that such a method does not exist in Person class, parse the name and create proper SQL with AND and LIKE operators on Person table, issue SQL and map to a list of Person instances. If this is not magic, go back to your Hibernate, as I find such features absolutely exciting and innovative.

I am just playing with Groovy, but I found this language to have many unexpectedly interesting parts. It is not a replacement of Java, but a great tool to combine and interact with its older brother.

* many thanks to my employer for sponsoring aforementioned books