jpereira.eu

A life committed to learning.

Programmer testing

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.

Continue Reading

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

My first WordPress Plugin

Today I managed to finished my first WordPress plugin. It’s not that difficult, even if you know little (close to nothing) about PHP. I started with one of many available plugins out there and started  tweaking the code, testing, more tweaking, more testing and voilá, my first wordpress plugin saw the light.

The plugin is simple, just to put in a client’s site where people can subscribe RSS feed, follow him in Twitter, become a facebook fan, etc, etc.

Here’s some screenshots:

First tab with some options

Second tab with a form (the code of the form can be configured)

And finally the configuration, in the admin area

If you want to get your first wordpress plugin running, just download the source code to get started.

Dowload it.

Continue Reading

Hacking a Rails controller and template inheritance strategy

Developing with Ruby on Rails can be fun, but sometimes, especially for newbies like me, we can get stuck somewhere. I’ll document my strategy for single model inheritance and how I did with the controllers and templates.

I have two types of users in my app, User (a common user) and ThingsAdmin (a user, but can have and administer Things). The two type of users basically share the same attributes and the same behavior, though the ThingsAdmin user can have and administer many Things.

For more about Single table inheritance, check the docs http://api.rubyonrails.org/classes/ActiveRecord/Base.html

Let me show you my code for the models:

class User < ActiveRecord::Base
   #attributes, validations, filters, methods and other stuff for User model
end

And the ThingsAdmin is something like this:

class ThingsAdmin < User
   has_many :things
   #Specific attributes, validations, filters, methods and other stuff for ThingsAdmin model
end

In the migration, I just needed to add a new field “type”:

  def self.up
    change_table :users do |t|
      t.string :type
    end
  end

It’s not needed to create a new table for ThingsAdmin.

Having these two models defined like this, when I create a new User, the field type is set to nil but If I create a new ThingsAdmin, the field “type” is automatically set to “ThingsAdmin”, i.e., the name of the model.

I can test this in the rails console:

irb(main):008:0> user = User.new
irb(main):009:0> user.type
=> nil
irb(main):008:0> admin = ThingsAdmin.new
irb(main):009:0> admin.type
=> ThingsAdmin

Now, I can have two different classes of users and it’s time to move to the controllers. I decided to start by mapping all things_admin resources to the controller User, something like this in my routes.rb:

resources :things_admins, :controller=>"users"

However, this does not works as expected because in my UserController the new action is something like:

class UsersController < ApplicationController
  def new
     @user = User.new
   end
   ##rest of the controller
end

So, how can I distinguish between the request for a new User or request for a new ThingsAdmin? My first though was to have a parameter moving around so I can differentiate the type of user I want to create, something like:

class UsersController < ApplicationController
  def new
      @user = User.new if params[:role]=='user'
      @user = ThingsAdmin.new if params[:role]=='admin'
   end
   ##rest of the controller
end

But this will bring some ugly things into my code, for example in the create action I would need to do something like:

class UsersController < ApplicationController
  def create
      @user = User.new(params[:user]) if params[:role]=='user'
      @user = ThingsAdmin.new(params[:things_admin] if params[:role]=='admin'
   end
   ##rest of the controller
end

I cannot forget about moving the param “role” when doing these operations…

So, I decided to try other solution, which I thing is cleaner. I created a controller for ThingsAdmin that only contains the actions “new” and “create”:

class ThingsAdminsController < UsersController
  def new
      @user = ThingsAdmin.new
      render "users/new"
   end
  
  def create
      @user = ThingsAdmin.new(params[:things_admin] if params[:role]=='admin'
      create_user(@user)
  end
   ##rest of the controller
end

And modified the UsersController to looks something like:

class  UsersController < ApplicationController
  def new
      @user = User.new
   end
  
  def create 
      @user = User.new(params[:things_admin] if params[:role]=='admin'
      create_user(@user)
  end
  protected
  def create_user(user) 
       #Code to create users (User or ThingsAdmin)
   end
   ##rest of the controller
end

Now, I have to tell the rails routing engine to redirect every action for business_admins to the UsersController except for “new” and “create” actions. My routes.rb look something like:

resources :users
match "/things_admins/new(.:format)" => "things_admins#new", :via=>[:get], :as=>:new_things_admin
match "/things_admins(.:format)" => "things_admins#create", :via=>[:post], :as=>:things_admins  
resources :things_admins, :controller=>"users", :except=>[:new, :create]

Now, every action concerned to a User or ThingsAdmin will be handled by the controller UsersController, except the “new” and “create” action.

There is something more I have to do, now concerning the update action. To have only one action handling the update of both User and ThingsAdmin, I just need to modify one line in the UsersController:

class  UsersController < ApplicationController
    
  def update
      @user = User.find[params[:id])
      ##This method is handling both the update of BusinessAdmins and Users....
      if @user.update_attributes(params[@user.class.name.underscore]) 
        flash[:success = "User updated"
        redirect_to user_path(@user)
     else
         flash[:error] = "Could not update user"
        render :edit
     end
  end
     ##rest of the controller
end

Now, everything works as expected. Really, I don’t know if this is the best strategy because it’s the first one I tried. If you have a better solution, please share because I would like to know.

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

Getting Rails 3.0.3 running with Mysql

Just as a memory aid for me and though I can share this.

While experimenting the Ruby on Rails 3.0.3, I created an application that by default uses SQLite, but I want to use MySql instead.

So here the steps I gone through:

1) Install MySql Server

sudo apt-get install mysql-server

2) Install MySql client dev package

sudo apt-get install libmysqlclient-dev

3) Create a new mysql user to use during my development and tests
3.1 ) Connect to mysql

mysql -u root -p

3.2 Create a user

create user 'railsuser'@'localhost' identified by 'somepass';

3.3) Grant all privileges to the user, so rails can do everything for me, such as creating the databases:

grant all privileges on *.* to 'railsuser'@'localhost';

4) Edit my app Gemfile:
Comment, or remove, the following line

gem 'sqlite3-ruby', :require =&gt; 'sqlite3'

Add this line:

gem 'mysql2'

5) Run the Bundler tool, the dependency management tool for Rails app:

sudo bundle install

Hopefully, everything went just fine till here.

Now, just configure my database.yml to use MySql as a database:

development:
adapter: mysql2
encoding: utf8
reconnect: false
database: myapp_development
pool: 5
username: railsuser
password: somepass
socket: /var/run/mysqld/mysqld.sock

test:
adapter: mysql2
encoding: utf8
reconnect: false
database: myapp_test
pool: 5
username: railsuser
password: railsuser1234
socket: /var/run/mysqld/mysqld.sock

For production, just use the MySql user that I want in production.

6) Let rake create my databases, by running:

rake db:create

It’s done.

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