Why I love test-driven development

Here is a very good example why I am a big fan of TDD (test-driven development). Instead of writing a specification or a requirements document I wrote the following test case and let Eclipse create a few new classes for me. Then I wrote enough code to get the basic functionality right and added a mock UserService with a few expectation set.

public class EnrollmentTest extends TestCase {
  public void testSignupTrialWithoutPayingOrganization() throws UserNotFoundException {
    PaymentDetails paymentDetails = new CreditCardDetails() ;

    Person firstPerson = new Person() ;
    firstPerson.setRfc822Address("sns@caimito.net") ;

    Person secondPerson = new Person() ;
    secondPerson.setRfc822Address("fidel@caimito.net") ;

    UserService userService = EasyMock.createMock(UserService.class) ;
    EasyMock.expect(userService.findUser(firstPerson.getRfc822Address())).andThrow(new UserNotFoundException()) ;
    userService.saveUser(new User(firstPerson.getRfc822Address())) ;
    EasyMock.expect(userService.findUser(secondPerson.getRfc822Address())).andThrow(new UserNotFoundException()) ;
    userService.saveUser(new User(secondPerson.getRfc822Address())) ;
    EasyMock.replay(userService) ;
		
    SignupManager signupManager = new PerUserSignupManager() ;
    signupManager.setUserService(userService) ;

    try {
      Customer customer = signupManager.signup(firstPerson, paymentDetails) ;
      User firstUser = customer.createUserAccount(firstPerson) ;
      assertNotNull(firstUser) ;
      assertEquals(firstPerson.getRfc822Address(), firstUser.getUsername()) ;
			
      User secondUser = customer.createUserAccount(secondPerson) ;
      assertNotNull(secondUser) ;
      assertEquals(secondPerson.getRfc822Address(), secondPerson.getUsername()) ;
    } catch (SignupFailedException e) {
      fail(e.getMessage()) ;
    } catch (UserAlreadyExistsException e) {
      fail(e.getMessage()) ;
    }
  }
}

This test case is very high-level. There is more to be implemented. The work of implementing the details can be distributed amongst the members of a team. That way everybody gets involved a bit, which is good to foster shared ownership of the code base, and it allows to delegate some easier tasks to Junior Developers.

Such a high-level test case can be used as well by a Senior Developer with more design experience to more precisely prepare a task for a learner. The high-level design is there and the Junior Developer can fill in the missing pieces and design a bit of the lower level parts. He will be able to learn good design and contribute working code to the project.

Java o PHP para desarrollar una aplicación web

Inspirado por la discusión con un cliente quiero publicar mis pensamientos sobre la cuestión "Java o PHP para desarrollar una aplicación web". Aquí en Panamá y aparentemente en otros países de América Latina PHP es mas famoso que Java. Hay muchas empresas pequeñas que se dedican a la creación de paginas web y ellos usan PHP para añadir funciones de interacción a las paginas. Todo esto me hace recordar la situación en Alemania hace como 8 anos atrás.

Creo que es importante que se comparan manzanas con manzanas.

PHP es principalmente una tecnológica para paginas web.

Java es un lenguaje como C/C++ o Smalltalk para realizar cualquier aplicación que se puede programar. Paginas web solamente son una forma de user interface. Con Java puedo crear aplicaciones desktop para diferente plataformas con Swing o RCP. Puedo crear applets para el browser. Y uso OOP (object-oriented programming) juntos con una cantidad de otras técnicas para crear un producto de calidad.

Java no se debe comparar con PHP. Mas bien con Microsoft .NET y alla con C# que es como el Java de Microsoft.

Veamos TDD (test driven development). No solamente ayuda eso para diseñar las clases - los objetos que se usan en el código - pero también puedo comprobar que el código no tiene errores. Herramientas como Cobertura, EMMA y Clover reportan la coberatura por unit tests. Un buen ejemplo es el reporte de Cobertura para el proyecto open source Tapestry.

Con una herramienta como Selenium puedo comprobar el user interface - o sea las paginas - de manera automática como si un robot seria usando toda la aplicación múltiples veces al día. Si se hace algún error, ya se lo ve dentro de una hora en el próximo build.

PHP frameworks como ATK y Smarty no solucionan el problema mayor de PHP: no hay separación de asuntos. La separación de asuntos me permite de desarrollar código que atiende los asuntos asignados a la capa en que reside.

Una clase en la capa de infraestructura comunica con la base de datos y retorna objetos de valores que se pasan a la capa de negocio. Yo puedo comprobar la funcionalidad de esa clase en aislamiento antes que se desarrolla el resto de la aplicación.

Una clase en la capa de negocio que requiere datos de una base de datos para poder trabajar se puede correr en un test con una simulación de la infraestructura, porque no depende directamente del código en la capa de infraestructura. Le puedo pasar un mock object que tiene la misma interfaz que el objeto real, pero actúa como defino en mi test.

Con TDD puedo verificar la función correcta de cada hielo en el código, porque me permite de usar cada linea de código en una forma de laboratorio. Y si hago cualquier cambio siempre y automáticamente se comprueba todo el código de nuevo.

Claro ideas como TDD, continuous integration, dependency injection y otras no son algo exclusivo para Java. Se puede usarlas con C, C++ y con PHP también. Pero porque la historia de PHP (scripting language para paginas web) dudo mucho que los que usan PHP tienen mucho experiencia con eso. Para la mayoría de los programadores Java también es algo nuevo - aunque la idea existe desde mucho tiempo.

Nosotros usamos la metodología Scrum y usamos técnicas generales como DDD, TDD y CI. Usamos Java porque es un lenguaje universal que nos permite aplicar eso en cualquier proyecto para cualquier plataforma y no nos limite a proyectos web. También usamos Java porque es un lenguaje OOP (object-oriented programming) y por este hecho nos ayuda diseñar en una manera limpia. OOP fue inventado como antes de 20 anos y hay muy buena experiencia con eso.

En PHP se ha cambiado mucho últimamente. Se ha extendido PHP para poder programar con objetos. Pero sin embargo en http://www.php.net se dice: "PHP is a widely-used general-purpose scripting language that is especially suited for Web development and can be embedded into HTML." Wikipedia tiene una buena definición para "scripting language".

Tags :

The impact of roadblocks on residential tourism

This is not meant as a rant, neither serious criticism. I can understand their reasons for doing this. Still it makes me think and, as I have to admit, feel a bit uncomfortable and less welcome.

Apparently Panamanian traffic police performs license checking campaigns preferably on major holidays. That's when you can see them on all major streets, but as well as in remote locations where you really wouldn't expect a roadblock. They make you stop and want to check your drivers license. I have no problem with that and see the reasoning behind these checks.

Another new measure to improve road safety is a new law that went into effect earlier this year. Every driver is required to carry a copy of the traffic rules in the vehicle. I guess the idea is to make people at least skim the book once in a while.

But what gets me mad is this: they ask you for your drivers license and if you happen to show them a foreign drivers license, the very next question is "For how long have you been in the country?". What has checking drivers licenses to do with immigration issues? And what might a potential residential tourist think who gets asked this kind of question on his very first visit exploring the country in a rental car?

There is an enormous amount of construction aimed at residential tourists going on. In Panama City alone there are more than 90 projects in progress that each will put about 200 apartments on the market. And then there are all the other projects in the countryside. I guess every other lawyer in the city works for foreign investors buying property of some sort. The majority of these people will buy a car and drive around ... If they decide to stay and buy property, they will receive their residency with all the national documents such as ID and drivers license at ease. But while this is in progress they are subject to the question "For how long have you been in the country?" I guess many people will questioning their decision to move here due to this less welcome feeling this treatment causes.

The police officers should be instructed to welcome tourists instead of treating them like illegal immigrants, which is what this question implies. In fact they did welcome bearers of a foreign drivers license last year. Now there is a lot of talk going on about foreigners being responsible for increased crime activity. But I doubt whether it's a smart move to harass people who present a US or European drivers license and beyond doubt look like visitors from these countries.

On the other hand Panama sees a lot of immigration from Colombia and Venezuela and there has been some negative attitude against Colombians amongst a lot of common Panamanians. From what I can tell - that's only casual observations - it's envy as many Colombians buy properties in the better neighborhoods and start businesses.

Still street opinion should not lead to this kind of questioning when checking for valid drivers licenses.

Tags :