A life committed to learning.

Category: java

Fluent interfaces while trying to make sense of Prototype Pattern

Sometimes I don’t have great opportunities to apply some nice concepts, but I have some time to learn them.

While trying to make some sense of the Prototype Pattern, I was doing some experiments and I needed, of course, the tests to prove my experiments.

It was when coding the tests, trying to define the client interface (not user interface :)), that to my mind came this article from Martin Fowler: Fluent Interface.

Well, what it matters are these two points:

  • Making your tests first helps you, a lot, to define not only the behavior, but also importantly, the client API.
  • Using Fluent Interface with a Builder, it’s a great way to send our message to the objects implementing the API.

Example of using a fluent interface:

package eu.jpereira.trainings.designpatterns.creational.prototype;

import static org.junit.Assert.*;

import java.util.List;
import java.util.Properties;

import org.junit.Test;

import eu.jpereira.trainings.designpatterns.creational.prototype.exception.CannotHaveZeroPartsException;
import eu.jpereira.trainings.designpatterns.creational.prototype.exception.CouldNotCloneLastObjectException;
import eu.jpereira.trainings.designpatterns.creational.prototype.exception.NeedToPackLastVehicleException;
import eu.jpereira.trainings.designpatterns.creational.prototype.exception.VehicleDoesNotHavePartsException;
import eu.jpereira.trainings.designpatterns.creational.prototype.model.Shell;
import eu.jpereira.trainings.designpatterns.creational.prototype.model.Tire;
import eu.jpereira.trainings.designpatterns.creational.prototype.model.Vehicle;
import eu.jpereira.trainings.designpatterns.creational.prototype.model.VehiclePartEnumeration;
import eu.jpereira.trainings.designpatterns.creational.prototype.model.VehiclePartPropertiesEnumeration;
import eu.jpereira.trainings.designpatterns.creational.prototype.model.Window;
/**
 * @author jpereira
 *
 */

public class ClientTest {

	
	/**
	 * Integration Test
	 * @throws CouldNotCloneLastObjectException
	 * @throws CannotHaveZeroPartsException
	 * @throws NeedToPackLastVehicleException
	 * @throws VehicleDoesNotHavePartsException
	 */
	@Test
	public void testCreateBUS() throws CouldNotCloneLastObjectException, CannotHaveZeroPartsException, NeedToPackLastVehicleException, VehicleDoesNotHavePartsException {
		Client client = new Client();
		
		//create a bus car
		//Create props for tire
		Properties tiresProps = new Properties();
		tiresProps.put(VehiclePartPropertiesEnumeration.SIZE,10);

		//Create props for shell
		Properties shellProps = new Properties();
		shellProps.put(VehiclePartPropertiesEnumeration.COLOR,"blue");

		
		Properties windowProps = new Properties();
		windowProps.put(VehiclePartPropertiesEnumeration.WIDTH,20);
		windowProps.put(VehiclePartPropertiesEnumeration.WIDTH,20);

		//client.createVehicle().with(new Tires()).times(4).
		Vehicle vehicle = client.vehicleBuilder().createVehicle().with(new Tire(tiresProps)).times(3).with(new Window(windowProps)).times(8).with(new Shell(shellProps)).times(1).packIt();
		
		//Get all windows
		List<VehiclePart> parts = vehicle.getParts(VehiclePartEnumeration.WINDOW);
		assertEquals(8, parts.size());
		 
	}
}

A hypothetical Builder implementation with a fluent interface:

package eu.jpereira.trainings.designpatterns.creational.prototype;

import java.util.ArrayList;
import java.util.List;

import eu.jpereira.trainings.designpatterns.creational.prototype.exception.CouldNotCloneLastObjectException;
import eu.jpereira.trainings.designpatterns.creational.prototype.exception.CannotHaveZeroPartsException;
import eu.jpereira.trainings.designpatterns.creational.prototype.exception.NeedToPackLastVehicleException;
import eu.jpereira.trainings.designpatterns.creational.prototype.model.Vehicle;

/**
 * @author jpereira
 *
 */
public class SimpleVehicleBuilder implements VehicleBuilder {

	private List<VehiclePart> vehicleParts;
	
	public SimpleVehicleBuilder() {
		this.vehicleParts = createNewPartsBag();
	}
	
	@Override
	public VehicleBuilder createVehicle() throws NeedToPackLastVehicleException{
		//Just check this is allways the first call on the builder
		if (vehicleParts.size()!= 0) {
			throw new NeedToPackLastVehicleException();
		}
		return this;
	}

	
	@Override
	public VehicleBuilder with(VehiclePart part) {
		this.vehicleParts.add(part);
		return this;
	}

	
	@Override
	public VehicleBuilder times(int times) throws CouldNotCloneLastObjectException, CannotHaveZeroPartsException {
		if (times==0) {
			throw new CannotHaveZeroPartsException();
		}
		//get the last one and clone it xtimes 
		if ( this.vehicleParts.size()>0) {
			
			VehiclePart lastObject = this.vehicleParts.get(this.vehicleParts.size()-1);
			//add it xtimes
			for (int i=0; i< times-1; i++) {
				//new object
				try {
					this.vehicleParts.add((VehiclePart)lastObject.clone());
				} catch (CloneNotSupportedException e) {
					//Could not clone it. Wrap exception
					throw new CouldNotCloneLastObjectException(e);
				}
			}
		}
		return this;
		
	}

	
	@Override
	public Vehicle packIt() {
		Vehicle vehicle = new Vehicle(); 
		vehicle.setParts(this.vehicleParts);
		//clear this reference for the chicle parts.
		this.vehicleParts = createNewPartsBag();
		return vehicle;
		
		
	}
	
	//Can be overriden by subclasses
	protected List<VehiclePart> createNewPartsBag() {
		return new ArrayList<VehiclePart>();
	}

}

That’s it

Continue Reading

You do not understand, yet, why do you need tests!

Why do I need tests in my software project? Keep bugs away? Yes! Keep quality high? Maybe. Can you define quality?

I see that people often justify the demand for a high test coverage with their desire to have quality in software projects, however they’re only seeing a part of the quality, the bugs visible to the customer. Quality, that word alone, can be very subjective, meaning different things to different people. Of course, having a bug free software means a high quality software, but if I have a bug free software and cannot add new features or improve existing ones, is this software a high quality software?

Now that we’re all doing “agile development” (right? at least you may think you’re doing, because you have daily meetings, review, sprints, etc), everyone should bear in mind one of the critical purposes of tests.

Big up-front designs do not work anymore, never worked for that matter (you soon loose integrity between the code and the design in the papers). We’re no able to make decisions based on the unknown (though some people may think they can), so we leave every decision to the last possible moment, until we have all, or most, information needed to make a reasonable decision.

One fundamental aspect of agile development is that you evolve your system as you go, you do it in iterations and every iteration is focusing only on what is needed to deliver the features you committed for that iteration. Your system will evolve, iteration after iteration.

With this evolution of your system, you will also evolve your architecture and design. You will not add database support on the first iteration if you don’t need a database, right? It’s waste. Right? So, from iteration to iteration your architecture and design will evolve, based on the features you have to develop and those you have developed. This is what evolutionary architecture and deign looks like, according to Martin Fowler.

But, how do you evolve your design and architecture? One of the key practices to do that is refactoring. Refactoring, again using Fowler’s knowledge, is “the process of changing a software system in such a way that it does not alter the external behavior of the code yet improves its internal structure. It is a disciplined way to clean up code that minimizes the changes of introducing bugs.”

Refactoring is one of the key practice of any project using any kind of agile development methodology, backed by testing and continuous integration. There is no way you can refactor your code if you do not have a safety net, i.e., if you don’t have something that keep you away from breaking existing functionality. This is a key point of tests, to allow you to evolve your system design and architecture.. Of course these test must be automated, needless to say that.

Continue Reading
Continue Reading

The problem with Java Web development frameworks is…

Well, from my point of view, the problem of Java Web development frameworks is that there are too many. Each one has its strengths and weaknesses, like anything else. I’m excluding those that are proprietary and you have to pay to use them. Really, why would people pay for such kind of thing?

Focusing on what is open source, you just need to see those supported by Apache: http://projects.apache.org/indexes/category.html#web-framework

Then you can see a list of Java web development frameworks (result of a Google search):
http://java-source.net/open-source/web-frameworks

There’s are so many and the community does not focus on building a complete Java Web Development Framework. The one I like more is Play! Framework because it’s a complete stack of java technologies that really help the development of web apps and it borrows many concepts from Ruby on Rails, which it’s my favorite.

I don’t know every Java web development framework, of course, and each must have their strengths and serve different purposes, but my feeling is that if there were only a few, then the community will focuses on improving those and we’ll end with a truly good framework.

Continue Reading

Yeahh, I’m building it with enterprise ready technologies… who cares?

If you have an web product idea and want to test it, i.e. put it in front of your users, what it’s the most critical aspect to consider first? I usually get my head into a conflict, because I’m used to work with the so-called “enterprise ready technologies”, namely JEE. My mind if formatted to think about all aspects that a good enterprise product should have. I start giving more attention to a set of quality attributes like performance, usability, reusability, testability, portability, modifiability, etc, etc, and give less attention to one critical aspect, if I want to get a product in front of the users fast: productivity.

So, I start looking to what is out there that is enterprise ready, like EJBs, JSF, Hibernate, JBoss, Tomcat, whatever, and start getting the pieces together…. out there in the world there was some a guy with the same product idea, but considered first the productivity aspect of the equation and started to materialize the idea with, let’s say, Ruby on Rails…. guess who’s the winner?

I’m not against the use of JEE, of course, I just think that in some cases it does not make sense. I also have this false argument in my mind: What if I start building it with PHP and then hit a performance problem with my 1Million users? Well, If I ever had one million users, I’ll be happy to deal with these performance issues 🙂

Continue Reading

Where’s my Java reflection?, Part II

Just to give the final implementation started in “Where’s my Java reflection“, here it goes the implementation of the generator for the method bindErrors (check last post “Where’s my Java reflection” to get into context):

private void composeBindErrorsMethod(TreeLogger logger,
			SourceWriter sourceWriter, TypeOracle typeOracle) {

		sourceWriter.println("public void bindErrors("
				+ parameterizedType.getQualifiedSourceName()
				+ " object, Map<String, List<String>> errors) {");

		// Get the fields declared in the parameterized type
		JField[] fields = parameterizedType.getFields();
		for (JField field : fields) {

			JClassType classType = field.getType().isClass();
			if (classType != null) {

				JClassType erroableType = typeOracle.findType(Errorable.class
						.getName());

				if (classType.isAssignableTo(erroableType)) {

					sourceWriter.println("if (errors.containsKey(\""
							+ field.getName() + "\")){");
					sourceWriter.println("object." + field.getName()
							+ ".setErrors(errors.get(\"" + field.getName()
							+ "\"));");
					sourceWriter.println("}");

				}
			}

		}
		sourceWriter.println("}");

Again, hope it helps anyone.

Continue Reading

Where’s my Java reflection?

Some people like it, others don’t. I like it, it’s so cool to make generic code, but as I ‘ve been experimenting with GTW to know it’s capabilities I found that GWT does not support Reflection. It uses instead a mechanism called Deffered Binding to overcome the lack of reflection.

When doing some kind of framework code with GWT, soon you’ll realize that you need reflection, as I did. Bad luck, you’ll have to dig into the underground features of GWT, namely deferred bindings and generators. You can learn the theoretical traits of Deferred Bindings in the documentation: http://code.google.com/webtoolkit/doc/latest/DevGuideCodingBasicsDeferred.html

Let me explain my scenario.

Continue Reading

Expressive programming in Java

In Ruby On Rails, for example, you can use a construct like this:

raise ActiveRecord::RecordNotFound unless condition

It’s simple to understand and easier to use, though you can also use the more classical format

if !condition
    raise ActiveRecord::RecordNotFound
end

Because of that I like also to use this kind of expressiveness in Java. Instead of thinking like:

if this then do that

I like to think like:

do that if this

Of course, is a matter of felling well while programming 🙂

Let’s take an example in Java. In this example there’s a simple API to put something in a cache and you will use a “key” to identify your objects in the cache. But because I, as API designer, don’t want you to use the string “key” as key, I will code the cache like this:

package eu.jpereira.exprogramming.cache;
public class MyCache {

  public static void addToCache(String key, Object object) throws Exception {
    if ( key.equals("key") ) {
      throw new Exception("Hey dude, key cannot be 'key'!!");
    }
    //do that cache thing
    System.out.println("Cool! You've added it to the cache!!");
  }	
}

But I prefer doing something like this:

package eu.jpereira.exprogramming.cache;
import static eu.jpereira.exprogramming.cache.ExceptionRaiser.*;

public class MyCache {

  public static void addToCache(String key, Object object) throws Exception {
    throwIfTrue(new Exception("Hey dude, key cannot be 'key'!!"),key.equals("key"),);
    //do that cache thing
    System.out.println("Cool! You've added it to the cache!!");
  }	
}

And the throwIfTrue method is coded like this:

package eu.jpereira.exprogramming.cache;

public class ExceptionRaiser {

  public static <T extends Throwable> void throwIfTrue(T exception, boolean condition) throws T {
    if (condition) {
      throw exception;
    }
  }
}

Even If at the first sight it may seems to be a lot of more work, it’ll pay off with my amusement while programming 🙂 Moreover, it’s easier to understand and to program like this.

Continue Reading

One line of code paranoia

If you have some java method like this:

public void doSomething(String oneArg, Object otherArg, Map<String, Object> mapArgs);

You can use your method somewhere in you code like this:

Map<String, Object> params = new HashMap<String, Object>();
params.add("key1", "Value1");
params.add("key1", "Value1");
doSomething("str1", someInstance, params);

Or if you’re paranoid about the number of lines of code you write, you can do something like:

doSomething("str1", someInstance, new HashMap<String, Object>(){{put("key1", "Value1");put("key1", "Value1");}});

Basically, you’re overriding the new anonymous HashMap and adding it a new initialization block…

Continue Reading

Look for the obvious first…

As I like to experiment cool web development frameworks, I decided to make a quick tour on Play! Framework. It was queued 🙂

So, here I was trying the persistence from the framework, that is basically JPA 2.0 with Hibernate as the persistence provider. I was also very interested in knowing what the framework could provide me for data validation, you know, that basic stuff that a framework should give us for free before it can be called wed framework.

I started with a very simple JPA entity like this one:

Continue Reading