Learn to use Dependency Injection

Learn to use Dependency Injection

Recently I placed a comment on this interesting blog from Uncle Bob Martin (Robert C. Martin). It contains a brief description on how I teach people how to use the Spring Framework.

Now, by popular demand (one person requested it over Twitter), I’ll guide you through the method and examples I use in this blogpost. It explains why people should use frameworks like Spring and/or Google Guice, and how.

Ordering Milk

Lets take a look at the application we have. We have a service:

package nl.redcode.examples.milkman;

public interface MilkRequestService {

	/**
	 * Process a new order.
	 * @param customer
	 * @param amountOfBottles
	 */
	public void processOrder(String customer, Integer amountOfBottles);

}

And we have a DAO (data access object) which will take care of persisting our order:

package nl.redcode.examples.milkman;

public interface MilkDAO {

	/**
	 * Save a new order.
	 * @param customer
	 * @param amountOfBottles
	 */
	public void saveOrder(String customer, Integer amountOfBottles);
}

The implementation of this DAO isn’t really interesting, lets just pretent it goes to the database:

package nl.redcode.examples.milkman;

public class MilkDAODatabaseImpl implements MilkDAO {

	public void saveOrder(String customer, Integer amountOfBottles) {
		//Puts order in database
	}
	
}

And finally we have our service implementation:

package nl.redcode.examples.milkman;

public class MilkRequestServiceImpl implements MilkRequestService {

	private MilkDAO milkDAO;
	
	/**
	 * Create a new service:
	 */
	public MilkRequestServiceImpl() {
		milkDAO = new MilkDAODatabaseImpl(
				//With SQLConnection or something
				);
	}
	
	/**
	 * Place a new order for milk.
	 */
	public void processOrder(String customer, Integer amountOfBottles) {
		//Log the order:
		System.out.println("LOG: Customer " + customer + " wants "
				+ amountOfBottles + " bottle"
				+ ((amountOfBottles > 1) ? "s" : ""));
		//Save the order:
		milkDAO.saveOrder(customer, amountOfBottles);
	}
}

Lets pretent that we are good obeying programmers, although we didn’t write our unit test up front, we are going to do it right away.

So… we want to test the service, how are we going to do this? Well, lets just create the service, call it, and then check if it does what we want it to do!

package nl.redcode.examples.milkman;

public class MilkRequestServiceTest {

	MilkRequestService milkRequestService = new MilkRequestServiceImpl();
	
	@Test
	/**
	 * Test our milk request service.
	 * Pre:
	 * - We have a customer that wants to order 5 bottles of milk
	 * Post:
	 * - The milk DAO got a request to save 5 bottles of milk
	 */
	public void testProcessOrder() {
		
		final String customer = "testUser";
		final Integer amountOfBottles = 5;
		
		milkRequestService.processOrder(customer, amountOfBottles);
		
		//Eeehh.... how do we check the call to the DAO?
		
		//HELP!!
	}
}

We run into a problem rather quickly. Now this code makes a connection to the database and it might or might not save our order. But how do we check this? We could go to the database and check…

NO! Never go to the database in a unit test. We only want to test a single unit of work, and the database ain’t one of them.

We need to refactor our code…!

The Factory

One possible solution to this problem is using a factory method. A factory creates objects so you don’t have to. Its best shown using an example:

package nl.redcode.examples.milkman;

import java.util.HashMap;
import java.util.Map;

public class MilkFactory { //no pun intended
	
	/**
	 * Here we save the mapping:
	 */
	private static Map<Class, Object> mapping;
	
	/**
	 * Create the mapping
	 */
	static {
		mapping = new HashMap<Class, Object>();
		mapping.put(MilkDAO.class, new MilkDAODatabaseImpl());
		mapping.put(MilkRequestService.class, new MilkDAODatabaseImpl());
	}
	
	/**
	 * Set a mapping by hand.
	 * Should only be used when unit testing.
	 * 
	 * @param <T>
	 * @param clazz
	 * @param impl
	 */
	public static<T> void replaceMapping(Class<T> clazz, T impl) {
		mapping.put(clazz, impl);
	}

	/**
	 * Not threadsafe ugly code-monkey code.
	 * @param <T>
	 * @param requestedClass
	 * @return
	 */
	public static<T> T get(Class<T> requestedClass) {
		if(mapping.containsKey(requestedClass)) {
			return (T)mapping.get(requestedClass);
		} else {
			throw new IllegalArgumentException("Doesn't exist");
		}
	}
}

So, lets dissect this.

The method get(class, object) will return an implementation for a given Class. It uses a Map to get the mapping. The map is created during the static initialization (yuk!) and contains the default mapping, but we can also provide our own mapping using replaceMapping(class, object).

Now how do we use it? Lets see our new MilkRequestServiceImpl:

package nl.redcode.examples.milkman;

public class MilkRequestServiceImpl implements MilkRequestService {

	/**
	 * Place a new order for milk.
	 */
	public void processOrder(String customer, Integer amountOfBottles) {
		//Log the order:
		System.out.println("LOG: Customer " + customer + " wants "
				+ amountOfBottles + " bottle"
				+ ((amountOfBottles > 1) ? "s" : ""));
		
		//Save the order:
		MilkFactory.get(MilkDAO.class).saveOrder(customer, amountOfBottles);
	}
}

As you can see we no longer need the constructor, we get the required DAO from the factory when we need it.

Now we can test it using the replaceMapping method:

package nl.redcode.examples.milkman;

public class MilkRequestServiceTest {

	MilkRequestService milkRequestService = new MilkRequestServiceImpl();
	
	//@Test
	/**
	 * Test our milk request service.
	 * Pre:
	 * - We have a customer that wants to order 5 bottles of milk
	 * Post:
	 * - The milk DAO got a request to save 5 bottles of milk
	 */
	public void testProcessOrder() {
		
		final String customer = "testUser";
		final Integer amountOfBottles = 5;
		
		//Better use a mock here, for example using Mockito or EasyMock.
		MilkFactory.replaceMapping(MilkDAO.class, new MilkDAO() {
			public void saveOrder(String customer, Integer amountOfBottles) {
				//Check if the customer = testUser
				//Check if the amountOfBottles = 5;
			}
		});
		
		MilkFactory.get(MilkRequestService.class)
			.processOrder(customer, amountOfBottles);
	}
}

As the comment says, you are probably much better of here using a mocking framework like EasyMock or Mockito. But the point is, we can test our class now without going to the database! We got our control back.

Dependency Injection

Instead of writing a factory, there is a better way to do this. It is the Hollywood principle “Don’t call us, we’ll call you”.

All the dependencies of the objects are injected into them instead of created (initial example) or retrieved (factory example). So our service will look like this:

package nl.redcode.examples.milkman;

public class MilkRequestServiceImpl implements MilkRequestService {

	private MilkDAO milkDao;
	
	/**
	 * The milkDao is given to us by our creator.
	 * 
	 * @param milkDao
	 */
	public MilkRequestServiceImpl(MilkDAO milkDao) {
		this.milkDao = milkDao;
	}
	
	/**
	 * Place a new order for milk.
	 */
	public void processOrder(String customer, Integer amountOfBottles) {
		//Log the order:
		System.out.println("LOG: Customer " + customer + " wants "
				+ amountOfBottles + " bottle"
				+ ((amountOfBottles > 1) ? "s" : ""));
		
		//We just use the milkDao we got:
		milkDao.saveOrder(customer, amountOfBottles);
	}
}

Now lets take a look at our test-code, it now looks like this:

public void testProcessOrder() {
	
	final String customer = "testUser";
	final Integer amountOfBottles = 5;
	
	//Better use a mock here, for example using Mockito or EasyMock.
	MilkDAO testMilkDao = new MilkDAO() {
		public void saveOrder(String customer, Integer amountOfBottles) {
			//Check if the customer = testUser
			//Check if the amountOfBottles = 5;
		}
	};
	
	MilkRequestService milkRequestService = new MilkRequestServiceImpl(testMilkDao);
	
	milkRequestService.processOrder(customer, amountOfBottles);
}

We now have full control over the wiring. First we create our own little testMilkDao (use a mock here!) and we place it into our service. That’s all. Instead of the hidden creation in the service itself or in the factory we are in full control.

But if you want to use this application you’ll need “something else” to create all the objects and do the actual wiring. Lets create our own Spring or Google Guice..!!

package nl.redcode.examples.milkman;

public class MilkApplication {

	public static void main(String[] args) {
		MilkApplication app = new MilkApplication();
		app.run();
	}

	public MilkApplication() {
		//-----   Provide wiring:  -----
		MilkDAO milkDao = new MilkDAODatabaseImpl();
		milkRequestService = new MilkRequestServiceImpl(milkDao);
		//------------------------------
	}
	
	private MilkRequestService milkRequestService;
	
	/**
	 * Do stuff:
	 */
	public void run() {
		milkRequestService.processOrder("Roy van Rijn", 1);
	}
}

Using Spring

The wiring we do in the constructor is what Spring and Google Guice would do for us. In the case of Spring you’ll write something like this:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

	<bean id="milkDao" class="nl.redcode.examples.milkman.MilkDAODatabaseImpl" />

	<bean id="milkRequestService" class="nl.redcode.examples.milkman.MilkRequestServiceImpl">
		<property name="milkDao" ref="milkDao" />
	</bean>
</beans>

Now you’ll still need to retrieve these “beans” from Spring, this can be done using our old-friend the Factory!
It’ll look something like this:

ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
	new String[] {"applicationContext.xml"});
MilkRequestService milkRequestService = appContext.getBean("milkRequestService");

This instructs Spring to load the XML file and create all the objects. Then we retrieve the milkRequestService and it is fully wired and ready to use!

Using Guice

Google Guice works exacly the same, only instead of using XML to define the mapping it only uses Java code and annotations.

First we tell Guice which implementations are the default implementations, for example:

package nl.redcode.examples.milkman;

@ImplementedBy(MilkDAODatabaseImpl.class)
public interface MilkDAO {

	/**
	 * Save a new order.
	 * @param customer
	 * @param amountOfBottles
	 */
	public void saveOrder(String customer, Integer amountOfBottles);
}

We also do this to the MilkRequestService. Next we tell Guice where to inject these implementations, in this case using ‘Constructor Injection’:

/**
 * The milkDao is injected by Guice.
 * 
 * @param milkDao
 */
@Inject
public MilkRequestServiceImpl(MilkDAO milkDao) {
	this.milkDao = milkDao;
}

Now if we want to use it, we retrieve it from Guice like so:

public class MilkApplication {

	public static void main(String[] args) {
		MilkApplication app = new MilkApplication();
		app.run();
	}
	
	/**
	 * Do stuff:
	 */
	public void run() {
		
	    Injector injector = Guice.createInjector();
	    MilkRequestService milkRequestService = 
	        injector.getInstance(MilkRequestService.class);

		milkRequestService.processOrder("Roy van Rijn", 1);
	}
}

Thats about it, you’ve seen:

  • Why you should use these patterns
  • How you would program them yourself (ugly monkey-code-style)
  • How using Spring (with XML)
  • How using Google Guice!

Good luck and happy programming!

ps. The code examples are just examples…!!


What if your favourite movie was remade as porno

What if your favourite movie was remade as porno

What if your favourite movie was remade as a porn movie? How would it be called, what would the title be?

My collegues and I were discussing this, and we came up with a top 10. We’ve also started a twitter hashtag.

Top 10

  1. Shaving Ryan’s Privates (everybodies favourite)
  2. The Curious Taste of Benjamin’s Bottom
  3. Honey, I shagged the kids
  4. Missionary Impossible III
  5. Good Will Humping
  6. Free my Willy
  7. Legally Boned
  8. I Know Who you did last Summer
  9. Schindler’s Fist
  10. Cliff Banger

Honourable mentions

And some honourable mentions to the titles that just didn’t make the list:

  • When Harry ate Sally
  • Saturday Night Beaver
  • Spankenstein
  • Swollow Hal
  • Sorest Rump
  • Bangs of New York
  • American Bangster
  • Thighs Wide Shut
  • Citizen Came
  • The Green Milf
  • The Porn Identity
  • Crouching Woman, Hidden Camera

Does my car hate me?

Does my car hate me?

Why does my car do this to me? It bugs me everyday. When I drive with the snow outside I have to use my windscreen washer quite a lot. When I pull the little lever behind my steering wheel it spurts a jet of antifreeze/washer fluid onto my screen and it starts to wipe for about 10 times. Then it stops… my window is clean again!

picture of dirty windscreen

But after about 15 seconds it does one final sweep… and this last sweep always leaves ugly marks!

Why do cars do this!!!? First it cleans my window perfectly, and then spoils it!

Update:
A collegue adviced me this: If the car has just finished wiping, quickly switch on the manual and stop it. This will still cause one extra wipe, but it comes right after the others. This produces a slightly better result.

I tried this two times on my car (a Fiat Bravo) and it worked one time, the other time it still did the final whipe after around 10 seconds.


MD5 quine, fixed point

MD5 quine, fixed point

MD5 quines

Sometimes I let my mind wonder and I get crazy questions. Today was a good example, I encountered a MD5 hash and I started to wonder, would there be a hash which would (when hashed again) be the same?

Thus: MD5(x) = x

This would be a kind of MD5 quine, when fed into the algorithm you get the original value back. This is actually called an MD5 fixed point.

Information I’ve found

So I started investigating, soon I discovered this website about collisions. Its well known that all hashing algorithms must have collisions, you can’t always produce a unique hash for input larger then the output of course.

The output of the MD5 sum is 128 bit (16 byte) long, so the input should also have the same length. But the MD5 algorithm is defined to have 512 bits as input. This isn’t really a problem because the algorithm will extend smaller input with padding. Lets assume the MD5 sum of any input is uniformly distributed over all possible sums, then the probability that a 128-bit string is a fixed point is 1/2^128. This isn’t a crazy assumption because all hashing-algorithms are designed to distribute the output as uniformly as possible to avoid collisions.

So, the probability that no 128-bit string is a real fixed point is (1 - 1/2^128)^(2^128). The probability that there IS a fixed point is 1 - (1 - 1/2^128)^(2^128).

Since the limit as N goes to infinity of (1 - 1/N)^N is 1/e, and 2^128 is most certainly a very large number, this probability is almost exactly 1 - 1/e = 63.21%.

But, of course, there is no randomness involved here - there either is a fixed point or there isn’t. But, we can be 63.21% confident that there is a fixed point. (Also, notice that this number does not depend on the size of the keyspace - if MD5 sums were 32 bits or 1024 bits, the answer would be the same).

Looking for the fixed point

I’ve just implemented a small program to look for these hashes, even though I know it will take millions of years to check all the numbers. But you never know, I might get lucky ;-)

The first algorithm I created took a single random String as input and kept applying the algorithm to the output. Eventually it will:

  1. Go into a loop
  2. Find a fixed point (which is a loop of size 1)

The weird thing is, if it ends up in a loop of size 1… I’ve found two things. Not only a md5 fixed point, which creates itself after applying the algorithm. But also an input-value that produces this md5 as output, a collision!

Graph

Another interesting thing would be a complete graph of all md5 answers. Which loops can we find, which md5 has most collisions etc. But this would take eternity to calculate, even using all the machines in the world.

Open questions

  • Are there loops? (It is possible there aren’t any loops at all…?)
  • Are there loops of size 1, a.k.a. fixed points?
  • Which/how many 128 bit combinations can’t be created with the input values?
  • Which/how many collisions will you get with all the input values?

More thoughts, errors, solutions..?


Splitting up Spring Web Flow & Facelets into JARs

Splitting up Spring Web Flow & Facelets into JARs

In our current project we want to have multiple Spring Web Flow-flows in one WAR-file. But we also want the flows and pages to be inside seperate JAR files, making the application a bit more managable and modulair.

This sounds straightforward but it took quite a bit of code and time…

First I created a single WAR-project with all the basic Spring, JSF and Facelet configuration. Like any Spring Web Flow (SWF) project we have a project-servlet.xml.

The first thing I did was changing our flowRegistry:

<!-- The registry of executable flow definitions -->
<webflow:flow-registry id="flowRegistry" 
   flow-builder-services="facesFlowBuilderServices" 
   base-path="classpath*:flows">
      <webflow:flow-location-pattern value="/**/*-flow.xml" />
</webflow:flow-registry>

The classpath*: allows SWF to search the whole classpath for flow-directories containing a flow definition.
In our case it would be: /flows/module1/module1-flow.xml

When you try to run this, and access a page we got the following exception:

Caused by: java.lang.IllegalStateException: A ContextResource is required to get relative view paths within this context; the resource was file [D:\projects\projectfromjar\module1\bin\flows\module1\page1.xhtml]
	at org.springframework.faces.webflow.FlowViewHandler.resolveResourcePath(FlowViewHandler.java:110)
	at org.springframework.faces.webflow.FlowViewHandler.restoreView(FlowViewHandler.java:74)
	at com.sun.facelets.FaceletViewHandler.restoreView(FaceletViewHandler.java:316)
	at org.springframework.faces.webflow.JsfViewFactory.getView(JsfViewFactory.java:93)
	at org.springframework.webflow.engine.ViewState.resume(ViewState.java:193)
	at org.springframework.webflow.engine.Flow.resume(Flow.java:545)
	at org.springframework.webflow.engine.impl.FlowExecutionImpl.resume(FlowExecutionImpl.java:259)
	... 38 more

For some reason Spring Web Flow doesn’t want to load the facelet. After browsing around Spring’s forums I came across some solutions. They didn’t do the trick, only when combining several methods I got it working for Spring Web Flow 2.0.7.

This is how I did it, we need to tell Facelets to use our custom ClassPathResourceResolver:

<!-- To load flows and pages from JARs, use this resolver -->
<context-param>
      <param-name>facelets.RESOURCE_RESOLVER</param-name>
      <param-value>nl.redcode.ClassPathResourceResolver</param-value>
</context-param>

The resolver itself is basic but does the job:

package nl.redcode;

import java.net.URL;

import com.sun.facelets.impl.ResourceResolver;

public class ClassPathResourceResolver implements ResourceResolver {

	public URL resolveUrl(String path) {
	    return getClass().getResource(path);
	}
}

This will help Facelets to translate a given path to a java.net.URL using the current classloader.
Spring Web Flow is currently giving us a FileSystemResource, and this doesn’t work because we want to load the pages with our classloader. For this we have the following wrapper:

package nl.redcode;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.ContextResource;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;

class CustomClassPathContextResource extends ClassPathResource implements ContextResource {

    public CustomClassPathContextResource(String path, ClassLoader classLoader) {
        super(path, classLoader);
    }

    public String getPathWithinContext() {
        return getPath();
    }

    public Resource createRelative(String relativePath) {
        String pathToUse = StringUtils.applyRelativePath(getPath(), relativePath);
        return new CustomClassPathContextResource(pathToUse, getClassLoader());
    }
}

To force Spring to use this Resource instead of FileSystemResource we use a post processor:

package nl.redcode;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.webflow.definition.registry.FlowDefinitionRegistry;

public class FlowRegistryClassPathPostProcessor implements BeanPostProcessor {
	
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
    
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if(bean instanceof FlowDefinitionRegistry) {
            alterRegistry((FlowDefinitionRegistry) bean);
        }
        return bean;
    }
    
    protected void alterRegistry(FlowDefinitionRegistry registry) {
        for(String flowId : registry.getFlowDefinitionIds()) {
            ApplicationContext ctx = registry.getFlowDefinition(flowId).getApplicationContext();
            overrideResourceLoader((GenericApplicationContext) ctx);
        }
    }
    
    /**
     * Override the ResourceLoader:
     * We know our flow is always defined as "flows/module1".
     * From the context we can derive the name of the flow (module1)
     * So we build up the ClassPathResource base as:
     * "flows/"+ ctx.getResource("")+ "/"
     * 
     * @param ctx
     */
    protected void overrideResourceLoader(GenericApplicationContext ctx) {
    	final ClassPathResource cpr = new ClassPathResource("flows/"+ctx.getResource("").getFilename()+"/");

    	ctx.setResourceLoader(new ResourceLoader() {
        	
        	public ClassLoader getClassLoader() {
        		return cpr.getClassLoader();
        	}

        	public Resource getResource(String location) {
        		return new CustomClassPathContextResource(cpr.getPath() + location, getClassLoader());
        	}
        });
    }
}

When the FlowDefinitionRegistry is created we provide it with a new ResourceLoader. When the resources are requested by Spring Web Flow we create our own CustomClassPathContextResource. This consists of our current location plus the defined location (viewId).

To register this post processor add it to your project-servlet.xml:

<bean id="flowRegistryClassPathPostProcessor" class="nl.redcode.FlowRegistryClassPathPostProcessor" />

How to use it

In our project we have the following flow(s) defined in a seperate JAR:
/flows/module1/module1-flow.xml

And our pages are in the same directory:
/flows/module1/page1.xhtml
/flows/module1/page2.xhtml
etc…

In the flow we can now use the following view-id’s:

<?xml version="1.0" encoding="UTF-8"?>
<flow 	xmlns="http://www.springframework.org/schema/webflow"
		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		xsi:schemaLocation="http://www.springframework.org/schema/webflow
							http://www.springframework.org/schema/webflow/spring-webflow-2.0.xsd">

    <view-state id="start" view="page1.xhtml"/>

</flow>

Its also possible to have pages in other places, you can define the views as relative paths. For example:
”../../shared_pages/page2.xhtml” turns into “/shared_pages/page2.xhtml”
”../pages/page3.xhtml” turns into “/flows/pages/page3.xhtml”

The only problem we still have using this method is the deployment with RAD/Eclipse WTP and Facelets auto-refresh. For some reason after deploying our application locks the files in the bin-directory. Eclipse then can’t delete this directory and fails to publish. Ending in one big #fail. But a simple clean, clean, republish, clean, rebuild, restart, shout, scream, cry, rebuild and republish will solve this.

The big advantage is the fact that the flows and pages are now defined in their own JAR files, making releases and sharing classes (like shared services/shared menu’s etc) much easier.

Information on Spring forum


Cleaner code: Inversion of logic

Cleaner code: Inversion of logic

Design patterns

Almost all programmers have heard about and used design patterns. And there are a lot of them. Famous design patterns include the Singleton, Observer, Template method. These are all patterns that focus on objects and the relationship between them.

There are more groups of patterns, for example take Dependency Injection (or Inversion of Control). This is an architectural pattern. They tell you things about the design of the whole program. And there are specific pattern groups, like concurrency patterns.

These patterns help you solve common problems in a well defined way, other programmers will recognise the patterns used and it will help produce more maintainable code.

Inversion of logic

The patterns described above all say something about classes/methods and architecture. But I think another class of design patterns exist, which have a smaller granularity. These patterns say something about the code inside a single method. A good example is Inversion of logic.

Let me give an example, lets take the following code:

public void processRequests(List<RentalRequest> requests) {
	
	for (RentalRequest rentalRequest : requests) {
		if(rentalRequest.isFormFilledCorrectly()) {
			Tenant tenant = rentalRequest.getTenant();
			if(tenant.getAge() >= 25 && checkLicenceStillValid(tenant)) {
				//Approve the request
				//Process the request in database
				//Send email to HQ
				//Etc...
			}				
		}
	}
}

Its a basic car-rental service and is has some logic before a request is processed. To make this code more readable and maintainable we can do two things. Of course it would be better to factor out the validation-logic into another piece of code. So lets do that first:

public void processRequests(List<RentalRequest> requests) {
	
	for (RentalRequest rentalRequest : requests) {
    
		if(validateRequest(rentalRequest)) {
			//Approve the request
			//Process the request in database
			//Send email to HQ
			//Etc...
		}
	}
}

private boolean validateRequest(RentalRequest rentalRequest) {
	if(rentalRequest.isFormFilledCorrectly()) {
		Tenant tenant = rentalRequest.getTenant();
		if(tenant.getAge() >= 25 && checkLicenceStillValid(tenant)) {
			return true;
		}
	}
	return false;
}

Some programmers don’t like the validateRequest() method above because there are multiple exit points. This was more problematic in C code then in Java because in C you needed to do a bit more resource management (freeing mallocs etc), in Java I actually don’t mind having more then one exit-point in my code. In this case it makes it just a bit more readable. It would be easy to add a ‘requestIsValid’ boolean and fill that instead.

Anyway, the next step in refactoring this code is using what I call “Inversion of Logic”. The idea is that you don’t continue nesting if something is true, but instead inverse it, and bail out if something is false. The big advantage is that you’ll lose a lot of nesting, making the code more readable. I’m going to do this in two places, first in the processRequest for-loop, and second in the validateRequest method.

public void processRequests(List<RentalRequest> requests) {
	
	for (RentalRequest rentalRequest : requests) {
    
		if(!validateRequest(rentalRequest)) {
			continue;
		}
		
		//Approve the request
		//Process the request in database
		//Send email to HQ
		//Etc...
	}
}

private boolean validateRequest(RentalRequest rentalRequest) {
	if(!rentalRequest.isFormFilledCorrectly()) {
		return false;
	}
	Tenant tenant = rentalRequest.getTenant();
	if(tenant.getAge() < 25 || !tenant.checkLicenceStillValid(tenant)) {
		return false;
	}
	return true;
}

As you can see in the for-loop all the business logic is moved one indent back, this will make your code easier to scan for business rules. And if you look at the validateRequest method the code reads more fluent. Instead of stacking up and remembering the valid cases:

IF form is correct
AND tenant age correct
AND tenant licence is valid
THEN proceed

We now eliminate the bad cases first:

IF form is incorrect: deny rental
IF tenant’s age or licence is invalid: deny rental
ELSE proceed

I’m trying to do this everywhere I can, it realy helps the readability.


Java EE 6 released, including Servlet 3.0

Java EE 6 released, including Servlet 3.0

Today marks the release of Java EE 6. The reference implementation (Glassfish V3) has been released and the specifications are going into their final state very soon.

About two years ago, while I was attending the JavaOne conference, I first heard about the Servlet 3.0 ideas. As a web developer I’ve worked a lot with these Servlets so I was curious about the ideas. But what I saw wasn’t what I hoped for. On the contrary, what I saw was a huge mistake in my opinion!

So I decided to contact the guys behind this JSR, to ask for some more information and share my views. Some time passed but I never got a reply… My next move was just to write about it, first on my own blog, then on DZone (05/30/2008) and on The Server Side a half year later, december 2008.

The only ‘reply’ I got from the people of the JSR was in the days following my (re-)post on The Server Side. Glassfish has a short re-cap on what happened here.

Now that the release is final I’m actually glad with the result. All the issues I raised from the early draft have been fixed. This is what a simple servlet would have looked like in the early draft:

@Servlet(urlMappings={"/foo", "/bar"})
public class MyServlet {
     @GET
     public void handleGet(HttpServletRequest req, HttpServletResponse res) {
          //Handle the GET
     }
}

And this was my suggestion on how to improve it (see second article/link):

@ServletMapping(name="myServlet", mapping={"/foo", "/bar"})
public class MyServlet extends HttpServlet {

     @Override //keep strong typing!
     public void doGet(HttpServletRequest req, HttpServletResponse res) {
          ...
     }
}

And this is from the final release:

@WebServlet(name="myServlet", urlPatterns={"/foo","/bar"})
public class MyServlet extends HttpServlet {

     @Override //keep strong typing!
     public void doGet(HttpServletRequest req, HttpServletResponse res) {
          ...
     }
}

That’s very similair, maybe a little too similair..? But anyway, I’m pleased about the result. It’ll be a lot easier in the future to write Servlets and Filters and a lot of cool new features have been added too.

I love the spec, despite the lack of feedback and replies from the expert group, ignoring all positive feedback and constructive advice. If I now look at the way the annotations turned out its almost identical to my first sketch after their JavaOne presentation in March 2008.


Steve Oakley, the head hunter

Steve Oakley, the head hunter

Every once in a while head hunters call me. They call you at home, at work, they work out your email adress and mail you… This will probably sound very familiar to most IT professionals.

Anyway, the thing that strikes me is that about 50% of the time a head hunter calls, its Steve Oakley! And it isn’t just me that is getting calls from Steve Oakley, no, all my collegues and friends are getting calls from him as well!

So, are you in or out? Have you been called by Steve Oakley yet?

I went to work, and all I got was a call from Steve Oakley


Testing with Spring

Testing with Spring

To improve the quality of your code it is important to thoroughly test your code. Not only using unit tests but also using integration tests. I’ll describe these terms and show examples on how to create tests using JUnit and Spring’s Test library.

Unit Testing

A unit-test is an automated test that tests one single unit-of-work. So, what is this unit-of-work? Its the smallest piece of code that can be distinguished. If you are programming in Java the smallest unit you can test is a single method. So all unit-tests should only test this single unit, and no other dependencies.

Here is an example of a unit-test:

public class CalculatorTest {

	private final Integer TOADD1 = 6;
	private final Integer TOADD2 = 4;
	private final Integer ANSWER = 10;
	
	@Test
	public void testAdd() {
		Calculator calculator = new Calculator();
		
		Integer returnedAnswer = calculator.add(TOADD1, TOADD2);
		
		Assert.assertEquals("The answer of " + TOADD1 + "+" + TOADD2 +
			" should be " + ANSWER + " but was " + returnedAnswer, 
			ANSWER, returnedAnswer);
	}
}

By adding the @Test annotation JUnit will know this is a unit test. When running the code we verify that it correctly adds two values.

Test Driven Development

Test Driven Development (TDD) is very important in modern software development. More and more people and businesses are using this technique to improve their code quality.

What TDD consists of, basically, is a very small development cycle for all your code. You just follow these steps:

  1. Write a unit-test that verifies your usecase
  2. Implement the interfaces you created for step 1
    (can be done quick and dirty, just to get the logic correct)
  3. Run the tests and confirm your code is logically correct
  4. Refactor your code into maintainable, readable, reusable code
  5. Confirm the code still works as designed by running the test(s)

Actually, I don’t write all my tests before the real code, but the process goes hand-in-hand. When writing code I always think about how I’m going to test it, and when the code is done, the test is too, combining step one and two. It speeds the process up a bit, and the code I end up with is almost the same because of the refactor-step.

Integration testing

With unit testing you can verify that the smallest units of work are correct. But this doesn’t give you any guarantees!

A famous example is NASA’s $125 million Mars Orbiter. It crashed when it was about to land on Mars. And why did it crash? Because one component calculated metric units and it feeded this information into another component that was using English units.

Very painfull for NASA, but a great example showing the importance of integration testing. Both NASA-components had been tested a lot, but apparently they neglected to test the components together.

Integration testing with Spring

Most business software in Java uses Spring. This is a framework glueing all your components together and providing dependency injection. This makes it easy to test all the classes and methods, but it makes it a bit harder to test the integration and communication between classes because you depend on the framework for that.

Luckely Spring helps us with a their Spring Test library full of tools that help you creating integration tests.

One thing you need in all integration tests is Springs Context. With Spring Test it is possible to wire some beans and let Spring inject those beans in your unit test. The old(-ish) way to do this is extending org.springframework.test.AbstractDependencyInjectionSpringContextTests or org.springframework.test.AbstractTransactionalSpringContextTests.

If you want to use these classes you need two things:

  • Create a seperate Spring configuration with test-beans (or use your normal Spring config)
  • Override String[] getConfigLocations(), provide it with the location of your Spring configuration.

Now, for all the private fields you have in your testclass Spring will attempt to auto-wire beans on it.

A small example:

public class PersonServiceTest 
	extends AbstractDependencyInjectionSpringContextTests {

	private PersonService personService;

	/**
	 * Integration test for my calculator.
	 * It also calls the calculatorDao which is in the calculatorService.
	 */
	@Test
	public void testAddPerson() {
		
		Person p = ...
		
		personService.add(p);
		
		//Test if the person has been added.
	}
	
	/**
	 * Provide the test with a configuration
	 */
	@Override
	protected String[] getConfigLocations() {
		return new String[] { "my-test-applicationcontext.xml" };
	}
}

Testing with Spring 2.5+

With the introduction of Spring 2.5 they improved the above method. For more flexability and a bit more control over the objects they introduced the SpringJUnit4ClassRunner.

This is how you would use it:

import org.junit.runner.RunWith;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= { "my-test-applicationcontext.xml" })
public class PersonServiceTest {

	@Autowired
	private PersonService personService;

	/**
	 * Integration test for my calculator.
	 * It also calls the calculatorDao which is in the calculatorService.
	 */
	@Test
	public void testAddPerson() {
		
		Person p = ...
		
		personService.add(p);
		
		//Test if the person has been added.
	}
}

It works the same way as before, but instead of having to override the AbstractDependencyInjectionSpringContextTests you now have a POJO. All the information about Spring and JUnit are placed in annotations on top of you class.

Hopefully I’ll find the time to write another post on mocking, including EasyMock and Mockito.


Feed your curiosity

Feed your curiosity

Curiosity is an emotion related to natural inquisitive behaviour such as exploration, investigation, and learning, evident by observation in human and many animal species.

Source: wikipedia

To me, curiosity is one of the greatest things we as humans have. It feeds you with knowledge and sparks your fantasy, its an emotion that tickles your brain and forces you to explore.

Curiosity isn't limited to humans

In life its vital to search for new things, new limits, new experiences. Always keep asking questions, because with every answer you find, more questions will arise!

At first this sounds a bit depressing, more questions for every answer you get. This doesn’t sound satisfactory, but trust me, it is! Its not the answer that gives you satisfaction, its the new array of questions that give satisfaction! Because these questions feed our curiosity.

It also strikes me that children are very good in asking questions, and they come up with the most amazing questions! I really think this is a good skill, and its a shame we lose this when we get older. Why don’t adults ask these questions? Is it the fear of the “dumb-question”, does it make them look stupid?

Here are some examples of good curious questions:

  • Q: How do blind people know when they’re done wiping toiletpaper?

 

  • A: They can feel it from the drag, and then wipe two times extra (just to be sure)

 

  • Q: If you smoke, and go into a coma. When you wake up, do you crave for a cigarette?

 

  • A: It depends, after 8 days all the nicotine would be out of him/her bloodstream. So the physical chemical craving wouldn’t be there when they wake up. They’ll probably still have a habitual craving though.

 

  • Q: Why don’t our eyelashes grow?

 

  • A: All hair follicles have a certain cycle. The hair grows for a certain time, and then it just drops out. Eyelashes have a short cycle-rate.

 

  • Q: Do fish drink?

 

  • A: It actually depends: Saltwater fish drink, and filter the salt and minerals with their gills. Freshwater fish absorb water with their bodies.

 

  • Q: How many neck-vertebrates does a giraffe have?

 

  • A: The same amount as we have, seven. Even a mouse has seven vertebrates. All mammals have seven vertebrates except the manatee and three-toed sloth (They only have six)

 

  • Q: Can Elephants jump?

 

  • A: No, they can’t! They weigh too much. Also they get very uncomfortable if there is more then one feet of the ground at any time.

 

  • Q: If you die from anti-freeze poisoning, would you be able to do cryopreservation?

 

  • A: ?

 

  • Q: A Dutch question: Waarom moet je bevroren eten altijd “ontdooien”? Dooien is het tegenovergestelde van bevriezen! Dus moet je iets toch dooien in plaats van ontdooien?

 

  • A: ?

If you have curious/weird questions, or know answers to unanswered questions, please drop me a comment!


Atheist look on Christmas

Atheist look on Christmas

Something other then the usual technical posts…
As you might already know, I am an atheist. Yes, in my opinion there is no God, there never was and (probably) never will be.

Atheistic Christmas?

Being an Atheist with Christian friends I get a lot of questions. Recently a friend of mine asked: “Why do you celebrate Christmas when you are an Atheist?”.

This question, to me, is quite simple. First of all, because it is a tradition. I think its a wonderful holiday. Ask around, what do people think about when you ask them about Christmas?

People think about:

  • Christmas trees
  • Snow!
  • Santa Claus
  • Toys, candy and gifts
  • Decorations, lights
  • Christmas dinner with relatives
  • The poor, and less fortunate
  • Christmas songs
  • The Grinch
  • Mistletoe
  • Christmas cards
  • Charles Dickens, A Christmas Carol

All of these things have no connection to the Christian Christmas, except the name “Christ-“.

The birth of Jesus

The date on which we celebrate Christmas is sometimes said to be the birthdate of Christ. But in fact this isn’t true. The date has been borrowed from other holiday’s. Originally people celebrated the Roman winter solstice on the 25th of December. It was probably just convenient to borrow this date.

So instead of saying I celebrate Christmas, I could just say I celebrate midwinter.

Santa Claus

Okay, how about Santa Claus, there is nothing more Christmas then Santa Claus. But again this figure has nothing to do with Christianity. The only thing God and Santa Claus have in common is the beard.

I’m from the Netherlands, and on the 5th of december the old Saint Nicolaas (or Sinterklaas) visits our country. At night he visits all the houses and he brings gifts for all the kids! Does this sound familiar? It should be, he and Santa are the same guy..!

sinterklaas

When New York City was still called New Amsterdam the Dutch tradition took off in America. Slowly evolving (yes, holidays evolve too!) into the Santa Claus we all know today.

And being Dutch I have a huge advantage, we celebrate Sinterklaas AND Santa Claus, getting gifts and candy twice!

But again, a good reason to celebrate Christmas, it is based on a old Dutch tradition, and Santa Claus has nothing to do with Christianity.

Family, friends and relatives

For me, the single most important reason I celebrate Christmas as an Atheist are my family, relatives and friends. Its the time of year, with its long dark days and cold nights, that is perfectly suited for spending time with friends and family.

Its also the perfect time of year to think about your own situation, about the people you know and love, about people who don’t have it as good as you have. Its the time of year of giving and sharing.

That is the most important reason to celebrate Christmas midwinter, winter solstice, late Sinterklaas.

god exits

Evolution…

Finally, I have to get something out of my system about evolution:

Please get over it, evolution exists, there is enough prove. Just because it is called a theory it doesn’t mean you can just throw it out of the Christmas decorated window. For example, did you know gravity is still a theory? It is, first it was known as Newton’s Theory of Gravitation, and after that a guy named Albert Einstein wrote a better version, the General Theory of Relativity. It is accepted that gravity exists and nobody doubts that. Just like gravity, evolution is not just a theory.


VMWare on your phone?

VMWare on your phone?

Recently VMWare, known from its computer virtualization software, has announced they are developing a dual-boot mobile version. This would allow you to run both Windows Mobile and Android on your phone.

But it isn’t going to be a dual-boot you know from your computer, they are planning on running the OS’es at the same time. This would allow you to switch between OS on-the-fly.

  • You want to use a Windows Mobile app? *click*
  • Oh, you want to use something on the Andriod platform? *click*.

I’m very curious how this will work out performance-wise, but the idea itself is great!

Via: computerworld.com.au


Eureqa

Eureqa

I’ve just stumbled across a new program: Eureqa

Its a program, developed by the Cornell Computational Synthesis Laboratory, that can detect equations in sets of data. Its primary goal is to identify the simplest mathematical formulas which could describe the underlying mechanisms that produced the data.

Its best described using their instructional video:

I’ve been playing around with it, for example trying to find a good prediction equation for the Son of Darts competition I blogged about earlier.

The algorithm(s) used in this program are based around “symbolic regression”. It is a form of Genetic Programming (GA) where the computer processes a tree of possibilities recursively searching for the best suited building-blocks.


#songsincode

#songsincode

songsincode

What is #songsincode ?

Last week I discovered a new hype on Twitter. The so-called “#songsincode”. It’s a huge hype under programmers and technical users. The best way to explain is probably by showing an example:

if( door == red ) {
   door.paint(black);
}

This obviously is Paint It Black by the Rolling Stones (if the door is red, paint it black)

My own #songsincode:

Here is a collection of the #songsincode I created and tweeted:

if( silhouetto == man && i.see(silhouetto)) {
   scaramouche.doFandango();
   if(thunderbolt && lightning) {
      me.frightened = true;
   }
}

while(true) {
   ableToCheckout();
}
//Unreachable code:
leave();

switch(random(2)) {
   case 0: feel.partner = null;
      break;
   case 1: feel.onlyFriend = city.of(this, angel);
}

for(mydaddy : oh) {
   whack();
}
jar.insert(whisky);

man.amount = 1;
man.come(love.name());
man.come();
man.go();

life++;
if(life > you && you != me) {
   me.goto(lengths);
   distance(you.eyes);
   if(me.saidTooMuch()) {
      me.setUp(it);
   }
}

for(Person p:people) {
   p.imagine();
}

boolean isLover(String name) {
   if("Billy Jean".equals(name)) {
      return false;
   }
   ...

for(int i = 0;i < 8; i++ ) {
   System.out.println("MMmmmMMmmm");
}
throw new RuntimeException("test dummy");

String bird;
bird = "word";

if(she != lovely && she != wonderfull && she != precious && she.age < 1 ...

Submarine submarine = new Submarine(new Color(255,255,0));
for(Person p:all) {
   submarine.add(p);
}

while( !me.like(mondays) ) {
   tellWhy(me);
}

while(young) {}
//loops forever

if(time == hammer) {
   System.exit(1);
}

if( !women ) {
   cry = false;
}

public static void main(String[] args) {
     this.remove(religion);
}

while(!hasFound) {
   lookFor();
}

if(grass=="green" && girls == "pretty") {
   takeMe(paradiseCity);
}

for(Leaf leaf:leafs) {
   leaf.setColor(new Color(139,69,19));
}
sky.setColor(Color.GRAY);

for(Thing thing:stuff) {
   aintGotNo(thing);
}
complainAboutGod();
for(Part part:bodyparts) {
   gotMy(part);
}
gotMy(life);
gotMy(freedom);
gotMy(life);

{
     final countdown = 10;
}

My favourite:

And here is my all-time favourite (in CSS!!) created by @codepo8:

.clowns{float:left;}
.jokers{float:right};
#me_you{position:fixed;margin:0 auto;width:100%}

I hope you liked them!


Java Generics for Compare

Java Generics for Compare

I’ve been developing with Java 5+ for quite a while now. Not all developers are this lucky, some are still stuck with 1.4… some even with 1.3! But my clients all made the excellent step forward to Java 5 (some even to 6). The problem is, they moved the runtime/JDK but forget to move their developers!

In Java 5 the language brings some good improvements, the for-loop is easy to understand, and almost all the developers are using this by now. The problem starts with generics. There is a part most developers understand, the Collections API. Almost all programmers use lists now as: List instead of a plain old List. This is a good start, but it must not end here! First, I must admit, generics in Java can sometimes be hard and confusing (when using <? extends X> and <? super X>). So I'm not going to talk about any of this 'hard stuff'. Its the use of 'easy' generics that can our lifes so much easier.

For example the piece of code below:

public class LabelPlaceholderComparator implements Comparator { 

    /**{@inheritDoc */
    public int compare(Object o1, Object o2) {
        LabelPlaceholder p1 = (LabelPlaceholder) o1;
        LabelPlaceholder p2 = (LabelPlaceholder) o2;
        return p1.getLabel().compareTo(p2.getLabel());
    }
}

Of course, there seems to be not much wrong with the code, I see it all the time. Yes, the code breaks if you put something else in the comparator, but hey… the Javadoc says it only accepts LabelPlaceholders! So lets use this code:

List holders = fillList();
Collections.sort(holders, new LabelPlaceholderComparator());

Done! Its working and no problems right? Not quite, your IDE (Eclipse in my case) complains about this code.
For example Eclipse says:

Type safety: The expression of type LabelPlaceholderComparator needs unchecked conversion to conform to Comparator<? super T>

At this point, most programmers at the company I work for now will just ignore this warning. They might even add:
@SuppressWarnings(“unchecked”)

What a shame… Lets just examine this warning, what is Eclipse trying to tell us here? The compiler doesn’t know we created the Comparator with only LabelPlaceholders in mind. But the compiler does know (with generics) that the List only contains LabelPlaceholders. So the warning is (in understandable English):

I’ve got a list here of T (LabelPlaceholders) and a Comparator for Objects, this can go wrong! I’d rather have a specific Comparator for this job. Do you have one for me?

The solution to this problem is very simple, but most neglect to use it:

public class LabelPlaceholderComparator implements Comparator<LabelPlaceholder> { 

    /**{@inheritDoc */
    public int compare(LabelPlaceholder p1, LabelPlaceholder p2) {
        return p1.getLabel().compareTo(p2.getLabel());
    }
}

As you can see, the code is much smaller. The interface is now generified, it knows we are going to compare LabelPlaceholders now, nothing more, nothing less. Also, we don’t have to cast anymore, because of the generics you can’t put anything else in there.

So, lets go to the conclusion: Why is the latter code better code?

  1. As you can see, the code is smaller!
  2. There are no casts, the code is safer (no ClassCastException or eleborate class checks)
  3. If somebody uses your code, he/she knows what kind of objects the Comparator can handle. You don’t have to read the Javadoc or the code to see what it does.

Throughout the projects I encounter I keep finding examples of places where generics would have made the code smaller/safer/more understandable. For some reason the programmers still only use generics on collections. So, even though generics aren’t perfect, please use them where/when you can, it’ll always add clarity to the code, and most of the time it’ll also make your code safer, and in some cases the code gets smaller because you can leave away casts and class-checks.

Don’t ever let me see public int compare(Object o1, Object o2); again!

(You see, it is possible for me to have a discussion about Java generics without mentioning reified generics!)