Archive

Archive for the ‘java’ Category

How to improve productivity when developing JEE based web applications

December 6th, 2011

The title of this post was stolen from Stackoverflow, from this discussion:

http://stackoverflow.com/questions/645746/how-to-improve-productivity-when-developing-jee-based-web-applications

I really like and agree with this point:

Being “the enterprise stack”, it is often used to create boring, ugly, “good enough” applications and, in general, enterprises tend not to attract great developers who love programming, and think and care about what they do. The quality of software in the enterprise world is not great.

There are exceptions, of course, but mainly from what I’ve seen from the past 10 years, this is, sadly, true. Why?

Agile, java, SCRUM, Software

Programming testing

December 3rd, 2011

Recently I’ve researched a little about programmer testing, which resulted in a slide set that I’m now sharing with you. These slides are the basis for a training, which included a lot of exercises, as I like to do.

It includes some information about:

  • Agile testing
  • Test driven development
  • Unit testing with JUnit
  • Test doubles and Mockito
  • Code coverage

If you have any feedback or question, please let me know by leaving a comment or send me an email.

Agile, java, programming, SCRUM, Software

Fluent interfaces while trying to make sense of Prototype Pattern

October 12th, 2011

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

Agile, java, programming, SCRUM, Software

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

September 14th, 2011

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.

Agile, java, Javascript, programming, SCRUM, Software

GWT Quickstart Project with Maven+GWT2.3+GIN1.5

July 14th, 2011

Hi,

Been a while… This post will show you, and remind me in the future, how to quickly setup a

GWT 2.3 project with Maven2 and GIN 1.5. I’m using Ubuntu, but the essential steps should be the same in any operating system.

Let’s start.

Assuming you have maven installed, just run:

mvn archetype:generate -DarchetypeRepository=repo1.maven.org -DarchetypeGroupId=org.codehaus.mojo -DarchetypeArtifactId=gwt-maven-plugin -DarchetypeVersion=2.3.0-1

Then, enter the details for you new GWT 2.3 project. Don’t forget that the property for ‘module’ should be a valid Java Class name, so use camel case when setting the name of module.
My configurations are something like:

Define value for property 'groupId': : eu.jpereira.gwt
Define value for property 'artifactId': : quickstart
Define value for property 'version': 1.0-SNAPSHOT:
Define value for property 'package': eu.jpereira.gwt:
Define value for property 'module': : Quickstart
Confirm properties configuration:
groupId: eu.jpereira.gwt
artifactId: quickstart
version: 1.0-SNAPSHOT
package: eu.jpereira.gwt
module: Quickstart

Now, we just need to add the dependency to GIN 1.5. Open the generated POM for the Quickstart project and add the dependency for GIN 1.5:

<!-- GIN Stuff -->
<dependency>
	<groupId>com.google.gwt.inject</groupId>
	<artifactId>gin</artifactId>
	<version>1.5.0</version>
	<scope>provided</scope>
</dependency>

Now you have a GWT 2.3 project with GIN 1.5 and Maven.
To finalize, let just remind how to setup GIN with the GWT project.
Generate the eclipse project:

mvn eclipse:eclipse gwt:eclipse

Open the project in eclipse and edit the *.gwt.xml (in my case, this is the file Quickstart.gwt.xml) file, located under “src/main/resources/” to import the GIN module:

<inherits name="com.google.gwt.inject.Inject" />

Create the GinModule, the class file that will configure the dependency injection for your application. You can have any number of GinModules. Check the documentation here: http://code.google.com/p/google-gin/wiki/GinTutorial
I like to keep everything related to GIn under the package *.client.gin. My Module is this:

package eu.jpereira.gwt.client.gin;

import com.google.gwt.inject.client.AbstractGinModule;
import com.google.inject.Singleton;
import eu.jpereira.gwt.client.QuaickstartApplication;

public class QuickstartGinModule extends AbstractGinModule {

	@Override
	protected void configure() {
		bind(QuaickstartApplication.class).in(Singleton.class);

	}
}

Here I’m only binding the QuickstartApplication object, which is my main application, like this:

package eu.jpereira.gwt.client;

import com.google.gwt.user.client.Window;

public class QuaickstartApplication {

	public void run() {
		Window.alert("Hello World!!!");
	}
}

Back to Gin setup, let’s create the Ginjector. Create a new Interface that extends from Ginjector:

package eu.jpereira.gwt.client.gin;

import com.google.gwt.inject.client.GinModules;
import com.google.gwt.inject.client.Ginjector;
import eu.jpereira.gwt.client.QuickstartApplication;
@GinModules(QuickstartGinModule.class)
public interface QuickstartInjector extends Ginjector{
	QuickstartApplication getQuickstartApplication();
}

Finally, it’s time to use it. In the Quickstart.java, which contains the entry point to the application, remove everything, create the injector and start your application.

package eu.jpereira.gwt.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;

import eu.jpereira.gwt.client.gin.QuickstartInjector;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Quickstart implements EntryPoint {

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		QuickstartInjector injector = GWT.create(QuickstartInjector.class);
		injector.getQuickstartApplication().run();

	}

}

Now, run the application with:

mvn gwt:run

And you should see the “Hello World!!” alert.

BTW, you can download the project here.

Happy coding!!!!

GWT, java, programming, Software, WEB 2.0

The problem with Java Web development frameworks is…

February 8th, 2011

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.

java, programming, Software, WEB 2.0

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

February 5th, 2011

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 :)

Agile, java, programming, Ruby, Software, WEB 2.0

Where’s my Java reflection?, Part II

January 30th, 2011

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.

GWT, java, programming, WEB 2.0

Where’s my Java reflection?

January 30th, 2011

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.

Read more…

GWT, java, Javascript, Software, WEB 2.0

Expressive programming in Java

November 20th, 2010

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.

java, programming, Ruby, Software