El buscador de profesionales a domicilio

Archive for the ‘Software Development’ Category



5
Apr

Compartir la visión de equipo

Para que un grupo de desarrolladores trabaje como un equipo, tal vez sea importante que  todos sus miembros tengan el mismo concepto de equipo.
¿Cómo es el equipo que queremos ser? ¿cuáles son las características que nos gustaría que tuviese cada persona del equipo?

Si tenemos una visión diferente de cómo debe funcionar el equipo, no conseguiremos llegar a ella porque cada uno rema en una dirección distinta.

Puede que tan sólo sea cuestión de detenerse un momento, reflexionar y decidir qué significa ser integrante de este equipo. Consensuar con los demás los valores y principios que
nos parecen claves. Y que de ese consenso busquemos prácticas que nos ayuden a ser el equipo que queremos y nos hagamos fuertes.

Un principio que me gusta aplicar es el de hacer con los demás lo mismo que me gustaría que hiciesen conmigo.

Así que voy a pensar cómo me gustaría que fuese un compañero de mi equipo para poner yo mismo en practica esos hábitos.
Voy a hacer mi propia lista de "me gustaría...", la cual podemos completar entre todos los miembros del equipo. Aquí va.

Me gustaria que un compañero... (o compañera, por supuesto)

  • Me pudiese cubrir perfectamente cuando estoy enfermo o de vacaciones sin que me tengan que llamar por teléfono contínuamente o pedirme que me conecte remotamente cuando no me encuentro en condiciones para ello.
  • Se tomase el tiempo de explicarme lo que sabe para que cuando se marche de vacaciones o se ponga enfermo, no me sienta totalmente perdido.
  • Me pidiese ayuda o hiciese programación en pareja conmigo cuando conozco mejor el código o el negocio que él o ella, porque así ganamos tiempo y aprendemos todos a la vez.
  • Me pidiese ayuda o trabajásemos juntos cuando sabe que el código que tiene que modificar es complejo y prefiere estar seguro de que no rompemos nada.
  • Me enseñase técnicas y prácticas que conoce para ser mejor profesional.
  • No me hiciese contarle más de tres veces una técnica de desarrollo sin que la tenga anotada y estudiada.
  • Trate de asegurarse por todos los medios que los cambios que ha introducido en el código no rompen funcionalidad existente (no introduce defectos).
  • Ejecutase los tests antes de subir su código al repositorio para evitar que me tenga que poner a arreglar tests que se han roto con cambios que no he hecho yo.
  • Tuviese la iniciativa de arreglar un test que no ha roto él o ella, cuando el compañero que lo rompió por accidente, ha sido avisado, pero no se puede poner con ello en ese momento. (Si quien ha dejado el test roto no suele romperlos sino que se trata de un caso excepcional).
  • Revisase mi código para entenderlo, detectar mejoras o sugerirme alternativas.
  • Criticase mi código constructivamente para ayudarme a mejorarlo y a superarme yo mismo.
  • Usase las partes de la aplicación que he hecho yo, para darme feedback como usuario.
  • Me pudiese sustituir en cualquier momento dándome la seguridad de que lo va a intentar hacer igual de bien que lo intento yo.
  • Esté abierto a recibir críticas constructivas y a aprender cada día.
  • Reconozca sus errores y se esfuerce por no cometer el mismo muchas veces.
  • Se alegre por mi progreso profesional y me apoye para que siga mejorando.
  • Tenga la iniciativa de aplicar cambios sobre código que he escrito yo, cuando necesita ser ampliado funcionalmente y yo no lo pueda hacer en ese momento (porque esté ocupado con otra tarea). Que no me haga sentir que soy el cuello de botella sino que me ayude a quitarme la presión de encima. Y que cuando cambie el código se asegure de que todos los tests siguen pasando y ha puesto el mismo nivel de cuidado en el código que el que he puesto yo.
  • Cuando tiene que introducir deuda técnica porque no le queda más remedio, lo anote y vuelva al código a saldarla tan pronto como el momento de presión termine.
  • Cuando tiene que modificar código de baja calidad se esfuerza por mejorarlo y no sólo por añadir a trancas y barrancas la nueva funcionalidad sobre la maraña.
  • Se cuestione si está haciendo lo mejor posible en cada momento y rectifica para ir en esa dirección.
  • No haya que repetirle las cuestiones con las que ya en otra ocasión hemos acordado que nos vamos a comprometer.
  • Escriba código que puedo entender sin tener que preguntarle a nadie. Y además lo puedo ampliar y testear con facilidad.
  • Antes de tomar decisiones que tienen repercusión sobre los demás, las discuta con los implicados.
  • Si no está de acuerdo con algo que digo, tenga la sinceridad de decirmelo a la cara en el momento adecuado, mejor que a destiempo.
  • Por tanto el equipo que yo visualizo se mueve en bloque, es homogéneo porque comparte unos valores y principios.

En mi visión de equipo no entra esto de "yo hago mi parte y tu la tuya", y cuando pasa algo en la parte que es "tuya" te llamamos para que la arregles tu. En una situación excepcional si, no hay reglas fijas ni matematicas puras para el día a día.

En esta visión tampoco hay tareas que siempre hace la misma persona porque es la única que sabe y parece que siempre va a seguir siendo así.
No puede haber personas que parecen ser imprescindibles. En realidad nadie lo es por muy alto que sea su bus factor. La vida sigue aunque unos marchen y otros lleguen.

Pero mi visión de equipo no sirve si mis compañeros no la comparten.

El compañero al que recuerdo con una sonrisa es el que me lo pone fácil en el día a día. El que no me obliga a verme sometido a presión innecesaria por un trabajo que él o ella ha hecho con neglicencia. Que no me obliga a hacer horas extra por su falta de cuidado.

Ser un amigo no tiene por qué ser lo mismo que ser un buen compañero. Ser un tío majo y agradable no significa ser buen compañero. Es de agradecer tratar con compañeros agradables pero eso no hace un buen equipo por sí sólo.

Puedes rellenar este interesante cuestionario sobre el nivel de agilidad de tu equipo y reflexionar sobre los resultados: http://www.abetterteam.org/new

Animaría a los equipos a redactar su propia lista de cualidades de un miembro del equipo y a colgarla en una pared grande, donde siempre sea visible para todos. Que nuestro ego no se pase por el forro esa lista sin que se note, sino que de el cante y podamos poner a ese ego en su sitio en favor de los valores del grupo.

No es otro que el ego quien causa problemas a individuos y grupos. Hay que vigilarle.

17
Mar

¿De verdad necesitas estar a la última?

La mayor barrera a la que un equipo se enfrenta a la hora de practicar XP o cualquier método ágil, son las personas. La falta de madurez y de compromiso imposibilita la paz sostenible de la que tanto se habla. Ambas, madurez y compromiso pueden a veces inferirse por el nivel de consumismo de los individuos.

Conozco demasiados programadores que van a la última en tecnología, pero que NO lo necesitan.

Probablemente cuando sacan de la funda el último móvil o el último portátil que acaban de comprar se sientan más importantes. Esto es lo que vende la televisión y la publicidad en general de las grandes marcas. Yo sin embargo no puedo evitar pensar que es una persona excesivamente consumista. A su vez eso puede significar que:

  • Aún vive con sus padres. Sus niveles de madurez, iniciativa y responsabilidad son mediocres.
  • Nunca se ha parado a pensar en el impacto que la fabricación de ese hardware tiene sobre el planeta y sobre los pobres chinos que están explotados fabricandolo. Esto es falta de compromiso con el planeta, que lo está pidiendo a gritos.
  • Es muy probable que jamás haya donado dinero para ninguna causa social, animal o medio ambiental. Ni siquiera a su proyecto open source favorito. De nuevo, poco compromiso. Puede que resultase ser un compañero demasiado egoista como para hacer un buen equipo.
  • Es demasiado materialista como para importarle el crecimiento personal de sus compañeros lo suficiente.
  • Es una persona que compra compulsivamente porque no tiene claras sus metas, no sabe por qué razón se levanta cada mañana.

No tienen que cumplirse todos los puntos, incluso puede que ninguno. Si los lees y te pica, entonces tu sabrás. Pero esto no es malo si te sirve para reflexionar sobre ello. Simplemente significa que tienes que deternete un momento y pensar más en lo que haces y en por qué lo haces. Que lo hagan todos tus amigos no significa que sea correcto. Has venido al mundo para hacerlo un sitio mejor, igual que mejoras el código legado cuando pasa por tu manos, aunque te llegue lleno de mierda hasta las trancas. Esos son los valores que necesitamos para practicar XP.

No necesitas mirar twitter cada 5 minutos. Piensa en la manera en que estas faltando el respeto a la persona que ha quedado para tomar café contigo, cuando estas escribiendo un tweet vació sobre el bonito uniforme del camarero. Los móviles que se vendían hacen pocos años tienen una batería que dura una semana entera. Se habla por telefono de puta madre y se pueden enviar mensajes SMS. ¿Necesitas poder consultar tu email en el tren? Ok, te vendrá bien un smartphone. ¿Pero de verdad no puedes esperar a gestionar tu email con tranquilidad? Seguramente el conductor del autobus se sentirá mejor si al subirte le das los buenos dias en vez de ir escribiendo en tu telefono nuevo. Puedes mandarle un tweet de buenos dias pero es más rápido que se los digas de boca a oreja.

No necesitas que tu portatil tenga 4 núcleos, 8gb de ram y una SSD de 200gb si trabajas con un pc de sobremesa que ya tiene las prestaciones suficientes. Si es tu herramienta de trabajo principal y realmente eres más productivo con ese hardware, adelante, se productivo. ¿Pero es de verdad tu necesidad? Los portátiles que fabricaban hace 6 años siguen corriendo perfectamente Linux y Windows. Con renovar la batería y ampliarle un poco la ram, van de lujo.

Ahora está de moda comprar un portatil Mac. Si vas a un evento y no tienes uno pareces un aficionado. Ya sabemos todos la polémica que hay con la fabricación de los Mac en cuanto al nivel de explotación en las fábricas y a pesar de ello... ¿es de culto tener uno?. Por desgracia pocas serán las marcas que se preocupen por las personas y el medio ambiente. Si eres más productivo con MacOS, está bien pero ¿no te vale con uno de segunda mano? ¿se van a reir de ti tus amigos? Yo no tengo un Mac, porque ahora mismo en el trabajo uso forzosamente Windows y en casa llevo una década usando Linux y encuentro que soy suficientemente productivo con el. Tengo Vim, Emacs y mucho mas! :-)
Por cierto que el stack tecnologico del trabajo me obliga a usar un pc sobremesa del copon gracias a que Microsoft no repara en recursos con sus sistemas operativos. Intentaremos usar Windows 7 por 20 años porque para la siguiente version, nos va a hacer falta un reactor nuclear. Es otra opción que hay que barajar, no actualizar de version Windows hasta que no quede otro remedio. De hecho Windows XP va estupendo para todo lo que no sea Visual Studio 2010.

¿Esto significa ser antiprogreso? Solo significa tomar las decisiones por motivos bien claros y no por parecer mas geek. Ser más geek mina los proyectos, las relaciones con los clientes, la relación con los compañeros y hasta calidad del software. ¿A ti te pega que Martin McFly llegase a casa con su skate volador y escribiese métodos de 5 lineas? A mí no.

¿Eres tu McFly con los aparatos mágicos? ¿tal vez el Inspector Gadget?

Si no te habías parado a pensarlo, ya sabes que eso no te hace más profesional a los ojos de todo el mundo. Para ser más profesional y una persona más integra, hay que prestar atención y practicar. En ello estamos. Si puedo ayudarte, grita, yo también estoy intentando aprender todo esto :-)

Aquí dejo un video que me parece fenomenal con Joán Melé hablando del dinero y la crisis. Yo la crisis no la estoy percibiendo economicamente en mi trabajo (sí en mi familia) pero sí que percibo una crisis tremenda en el sector por una falta de valores que nos permite ser ágiles de verdad.
 

 

10
Feb

Linq to Sql Horrors

Linq to Sql is a kind of ORM for .Net by Microsoft. Working with Linq to Sql can be a nightmare.

  • The basics:

In order to send or retrieve objects to or from the database, you need a DataContext instance. This is an instance of a class that inherits DataContext. It is created by Visual Studio with drag and drop. One context is generated for every database you access to. This generated context is inside a .cs file which contains also the classes that map database tables. The mapping is contained in a .dbml file (xml) generated in the same folder. You should not change any of this generated files. If a table changes in the database you must regenerate with the IDE.

Select example:
If the name of the database is ProductionDB, the DataContext will be ProductionDBDataContext.

var context = new ProductionDBDataContext(connectionString);
var userEntity = (from user in context.Users
	where user.name == "carlos"
        select user).First();

Insert example:

var context = new ProductionDBDataContext(connectionString);
var user = new User();
user.name = "manolo"; 
context.Users.InsertOnSubmit(user);
context.SubmitChanges();
  • The main issue:

The same context instance have to be used for all the operations performed on a relational object instance. This would throw an exception:

var context = new ProductionDBDataContext(connectionString);
var userEntity = (from user in context.Users
	where user.name == "carlos"
        select user).First();
// Imagine this is part of another method in another place
// but with the same userEntity instance that was passed through:
userEntity.age = "30";
var otherContextInstance = new ProductionDBDataContext(connectionString);
otherContextInstance.Users.InsertOnSubmit(user);
otherContextInstance.SubmitChanges();

So you can't just pass relational objects from one method or layer to anoter, you have to always cope with the "same context instance problem".

  •  Solutions
  1. Pass the context instance along with the relational objects, in all the places where you need to perform database access:   someMethod(user, context);
    Bad choice:
    This leads to spaguetti code quickly. Why  does my business layer have to know about a database context?
  2. Ok so we can make a Singleton for the context instance and make sure it is the same for all the application:
    public static ProductionDBDataContext AppContext = new ProductionDBDataContext(connString);
    Bad choice: When more than one request hit the server at the same time you get concurrency problems. The context will be trying to insert in one thread while trying to update or select in other. Weird race conditions happens and exceptions are thrown.
  3. Create a context for every thread. Every thread will have its own context Singleton. We found this solution thanks to Rick Strahl and his great post. However Rick's code can be simplified this way:
public class ContextFactory
{
	[ThreadStatic]
	private static ProductionDBDataContext context;
	private string connString = "settings to access the database ...";
 
	public static DataContext Context(){
		if (context == null)
			context = new ProductionDBDataContext(connString);
		return context;
	}
}

The ThreadStatic attribute ensures that every thread will access a different instance. So the "context" is not shared amont threads. This simplifies Ricks's code. But our problems didn't stop here unfortunatelly :-(

You might expect the thread to die when the response is sent back to the client side, but it doesn't. Sometimes IIS reuses the thread for other requests, and the context is not a new, fresh instance. Moreover, the context caches some queries and that leads to several issues:

  1. The optimistic concurrency control nightmare. The default behavior is for "Linq to Sql" to check every db column on update, to see if there are more than one simultaneous attemp to persist the entity. If so, it raises the ChangeConflictException. This can be avoided by editing the dbml and marking every column with "Never" in the UpdateCheck property. Guess that.... when you regenerate the dbml file, this is overwritten and you loose your configuration. More information on conflicts here.
    One way to deal with conflicts is to catch the exception and force the update:

    var someEntity = ... // query here
    try
    {
        context.SubmitChanges(ConflictMode.ContinueOnConflict);
    }
    catch (ChangeConflictException e)
    {
       context.Refresh(RefreshMode.KeepCurrentValues, someEntity);
    }

    However, this does not avoid the cache invalidation problem.

  2. The cache invalidation problemis the last one we have found and solved so far. The solution is to drop the cache as the new request enters the server. To refresh the cache just create a new instance of the context:
    public class ContextFactory
    {
    	[ThreadStatic]
    	private static ProductionDBDataContext context;
    	private string connString = "settings to access to database ...";
     
    	public static DataContext Context(){
    		if (context == null)
    			context = new ProductionDBDataContext(connString);
    		return context;
    	}
    	public static void FlushContext(){
    		context = new ProductionDBDataContext(connString);
    	}
     
    }

    Then, in the first layer of the server side (where the request is received) we call FlushContext to make sure it is new for this request. (For us is our JsonRpcController, a custom make controller hierarchy).

For now, we can rest assured that our DataContext is:

  • Unique for every thread so it is thread-safe.
  • Unique for every request so there are no cache problems among different requests.
  • If two different parts of the application need a context's instance in the same request, our factory gives a single reference (Singleton), making sure that only the first access initializes it (because we check whether it is null before instantiating).
27
Jan

Un solo valor de retorno

Hay un mal que se esta extendiendo por la aplicación en las últimas semanas. Es el ResponseDTO. Es un objeto plano, tiene un campo "success" de tipo boolean y un campo "message" de tipo string. Debía llamarse Response pero colisionaba, así que se quedó con un mal nombre. Si le hubiesemos llamado ControllerResponse seguramente no se hubiese usado en las otras capas de la aplicación porque hubiese dado más pistas a quienes lo fuesen usar, de que su lugar es la capa controller. Sin embargo se ha colado en muchas capas de backend y no es una buena práctica:

Los metodos y funciones deben devolver un solo resultado y en ocasiones, ninguno (void). ResponseDTO se puede considerar "un solo resultado" cuando los campos "success" y "message" se necesitan el uno al otro, tal que no tiene sentido el objeto sin los dos campos. Es decir cuando el objeto es lo más atómico que la operación puede devolver. ResponseDTO se ideo para enviar a cliente (js) respuesta a determinados comandos que solicita al servidor pero no debería usarse en las otras capas de la aplicacion.

¿Dónde lo usamos mal? Tenemos métodos con un nombre interrogativo que denotan retorno boolean y sin embargo devuelven uno de estos ResponseDTO:

  • IsExistingUser
  • DoesPolicyExists
  • IsValidInput

Para cualquiera que lea la API, no es intuitivo. ¿Para qué sirve el "message" del objeto cuando el método "IsExistingUser" retorna? Para nada.

En la validación, puede tener sentido este objeto response dependiendo del contexto: Si el error de validación puede considerarse una circunstancia excepcional, entonces lo mejor es lanzar una excepción que alguien de nivel superior recogerá. Por tanto, sobra el objeto response ya que la excepción llevará el mensaje de validación particular. Si un problema de validación no se considera una circunstancia excepcional, entonces puede estar bien devolver el response con su success puesto  a false y su mensaje concreto.

Más sitios donde lo usamos mal: Métodos que disparan acciones hacia fuera de nuestro sistema

  •  SendEmail
  •  SaveUser

Los métodos que provocan acciones que salen de los límites de nuestro código (acceso a BD, a un servidor de correo, etc) no pueden garantizar la correcta consumación de la acción. Por tanto, jugar a devolver boolean para exito o fracaso es engañarnos.
Es preferible un método void que funciona sin hacer ruido cuando todo va bien y que lanza excepciones cuando se encuentra con una situación inesperada. Por ejemplo, el método que solicita el envio de un email, puede defenderse de excepciones que provoque la libreria de SMTP y traducirlas en excepciones de nuestro dominio, tales como EmailSendFailure (una excepción nuestra que hereda de ApplicationException).

¿Y es tan grave que usemos el ResponseDTO? Sí que lo es porque el código que consume esos métodos se convierte en spaguetti:

var isNotValidData = !InputValidator.ValidateUserData(
                          policyHolder.Person).success;
if (isNotValidData)
{
	response.message = Strings.T("Los datos son incorrectos.");
	return response;
}

Del método "ValidateUserData" sólo nos interesa el campo "success", el mensaje lo está generando el llamador. No sólo es raro de leer sino que es un coñazo a la hora de escribir tests de interacción. Cuando queremos que en un test de colaboración, este método devuelva falso, tenemos que especificar que devuelva un objeto con un campo a falso. Si fuera boolean, no tendriamos que especificar nada porque el valor por defecto sería false. Esto va al hilo del posts de los tests de interacción limpios.

En el caso de métodos de acción como el envio de email, es incluso peor porque quien consume el método pensará que con un resultado verdadero el email ha llegado a su destino, como si eso lo pudiesemos asegurar de alguna manera.

Para saber qué debe devolver un método, este debe tener una única responsabilidad y debemos saber cual es. Y la mejor manera de saberlo, para mi siempre es escribir el test antes que el código.

 

26
Jan

Cleaner interaction tests

Note: this post will probably evolve, the text will be updated as I need it.

In order to write cleaner interaction tests (those which use test doubles; mocks, spies, stubs) you should understand how your test doubles framework works. Interaction tests can be extremely difficult to read and maintain and very fragile if you don't pay enough attention. We will review Mockito, Moq, Jasmine and pyDoubles.

Mockito and Moq create a double object by inheriting the original and overriding its methods. pyDoubles uses interception rather than inheritance. Jasmine is different because it does not double the whole object, but just the method you spy on. So there is a big difference: Mockito, Moq and pyDoubles replace the whole object while Jasmine replaces just one method.

So Jasmine leaves space for a bad testing practice: Spy on one method of the object while testing other method of the same object. Interaction tests are intentded for object collaboration. Testing that one method calls another method within the same object is not recommended. It means that the object has more than one responsibility or that you want to know more about the object's inner behavior than you should, so you are breaking encapsulation. This is not a Jasmine problem, the problem is yours if you don't use the tool properly.

There are three primary reasons to replace method calls on collaborators:

  1. You want to avoid a database call just to keep the test unit fast and repeatable (stub the method - use a stub object)
  2. You want the method to return some value to simulate the response (stub the method - use a stub object)
  3. You want to make sure that a call is made (spy or expect the call - use a spy or a mock object)

For case numer 1, you don't have to specify the returned value. Just use the stub object and let the framework return whatever it wants. Mockito and Moq, return the default value for the method, when no other behavior is specified:

  • If the method returns an integer, a call to that method in the stub object, will return cero (default value for integers)
  • If the method returns an object (reference type), a call to the stub method will return null (default for objects)
  • False for booleans and so on...

However, be careful with Moq because in C#, if the original method is not virtual (contains the virtual keyword), Moq can't stub it out, so the original will be called. Moq fails if you specify a behavior on that method but if you don't, it calls the original instead of returning the default value.

pyDoubles always returns None no matter the method signature.

For case numer 2, you define what the returned value should be. Using "when" in Mockito and "Setup" in Moq.

For case numer 3, you verify that a call was made:

  • Mockito: verify(double).method();
  • Moq: double.Verify(x=>x.method());
  • pyDoubles: assert_that_method(double.method).was_called()
  • Jasmine: expect(double.method).toHaveBeenCalled()

You might want to know what parameters were passed in too. In this case you can use Matchers in Mockito, Moq and pyDoubles.

Moq sample:

userRepository.Verify(x => x.SaveNewUser(
        It.Is<Person>(
        p => p.PersonalIdentificationCode == "TEST_CODE")));
 

pyDoubles sample:

assert_that_method(double.method
         ).was_called().with_args(obj_with_fields({
                            'id': 20,
                            'test_field': 'OK'}))

For Mockito samples I am waiting for my friend @regiluze to write a post on it :-) I will link it here when written.

Jasmine sample:

spyOn(double, "method").andCallFake(function(){
      expect(arguments[0].name).toEqual("Carlos");
});

Test collaborations one to one:

If the object under test has more than one collaborator, tests can be really hard to understand. I recommend expressing every collaboration in a single test:

  • A talks to B (test 1)
  • A talks to C (test 2)
  • For test1, B will be a spy o mock (you use Verify at the end). Also for test1, you don't care about C, C is just a dummy. Calls to C don't need to be configured in the double, let the framework return the default value.
  • For test2, C is the spy or the mock, you verify interaction between A and C, and do't care about B. Calls to B don't need to be configured, let the framework return whatever.
  • For test1, if the value returned by C, is necessary for the collaboration between A and B, then Ok, specify the stub result for that call to C, and verify on B.

Group the tests by setup:

Should I have a test class for every class in the production code? NO.  Tests must be grouped by their setup. This is, put those which have the same arrangement in the same test case (test class). If there are two or more interaction tests in a class, the creation of the SUT and the doubles, should not be in every test. It must be in the setup, along with the injection (doubles, are injected to the SUT as collaborator). So, if you find yourself injecting the test double to the SUT in more than one test, watch them again carefully.

 

 

22
Jan

Apego a la herramienta

Cuandó programaba en Delphi arrastrando componentes gráficos para programar las aplicaciones de escritorio, me parecía tan potente y tan sencillo que no quería cambiar de herramienta (allá por 2001). Por motivos de trabajo tuve que saltar a Gnome, con Gtk (en un principio con C++ y Gtkmm) Me parecía un atraso volver a aprender nuevas herramentas para hacer cosas parecidas y se mi hizo dificil. Sin embargo, el cambio me trajo nuevos conocimientos, nuevas ideas para abrir la mente. En medio de todo estó también programé aplicaciones Java + Swing, tanto cuando no había editores de GUI visuales como cuando los hubo. Pasé por Mono y Gtk#, luego a la web con Castle.MonoRail y eso me llevó con el tiempo a MS .Net y Windows.Forms.  Siempre por motivos de trabajo, un poco en contra de lo que me apetecía. Contínuamente a aprender y encima saltando a la plataforma propietaria de Microsoft, el "maligno" (yo que ?olo tenía Linux en mi maquina desde hacía años).
Gracias a las herramientas de Microsoft pude aprender conceptos como el Data Binding que hoy en día aplico en Javascript y llegué a aprender y dominar los genéricos, que le dan mil vueltas a los de Java. Incluso me hice un framework para escritorio que me permitiese testear automaticamente mis aplicaciones.
Después por motivos de trabajo, tuve que abandonar .Net y salté a Python + Django, para trabajar ya en la web. Nada que ver con lo anterior. Nada en absoluto. En todos estos años también he tenido que trabajar con Applets Java, con PlayFramework, con Weblogic, con Spring y en los últimos meses, muchísimo Javascript.

Cada cambio era una patada a mi ego, porque me sacaba de la zona de confort y me hacía sentir que perdía mi valía, la maestría de la herramienta que tanto me habia trabajado.

Y resulta que en lugar de perder, estaba ganando. Si no hubiese tenido que pasar obligado por todos estos cambios, no tendría la visión que tengo hoy en día sobre patrones, técnicas de programación, arquitecturas ... la tranquilidad de que me cuesta muy poco adaptarme a una nueva plataforma porque siempre contiene elementos de otras que ya conozco. Me da seguridad en mi mismo y me ha quitado por completo el apego a las herramientas. Programo en lo que sea y estoy deseando seguir aprendiendo lenguajes, frameworks.

Disfruto programando cualquier lenguaje y sé qué elementos me interesan usar de un framework y qué otras partes me puedo saltar. Solo porque he tenido que trabajar en muchos.

Ahora que estamos buscando gente para que se una a nuestro equipo, donde usamos mayormente .Net con C# y por otro lado Javascript, sé que mucha gente no tiene interes porque no quiere abandonar su stack tecnológico de siempre. Parece que programar .Net fuese lo peor del mundo, cuando es tan solo una copia de Java que lo mejora en muchos aspectos. Se van copiando el uno del otro. Además puedes usar F#, IronPython, IronRuby, Boo, y aprender de algunos de los programadores más increibles del planeta.

Me parece muy bien que la gente tenga predilección por frameworks como, Django, Symfony, Rails o Grails pero la negativa a usar otra cosa, tal como yo lo veo, es una cuestión de apego  poco racional. En algunos casos, yo diría que inmadurez. Además, los proyectos no duran para siempre, son etapas, son transiciones como la vida misma.

Todos los que me habeis dicho personalmente (amigos mios) que nos veníais por el stack tecnológico, creo que aún teneis que seguir madurando profesionalmente.  Y yo tambien, por supuesto. Lo digo sin rencor ni enfado de ningun tipo.

Contínuamente me digo a mí mismo... no dejes que el ego frene tu aprendizaje :-)

16
Jan

Mockito Vs Moq

Don't be confused, the title is just to get your attention. This is not a benchmark between Mockito and Moq. I need to  explain some differences to my teammates so that the transition between Mockito and Moq is softer for them.

Typical way to stub out a method call with mockito:

when(colaborator.method(argument1)).thenReturn(whateverIwant);

Same with Moq:

colaborator.Setup(x => x.method(argument1)).Returns(whateverIwant);

Obviously, the mockito way is nicer. I believe this is because of Java capabilities but I am not sure. I would like to dig into mockito's source code to see how is this possible. I will do it and blog about it soon. I used to think that it was because of the kind ot late binding supported by Java, but I am not sure.

Moq uses a lambda expression (anonymous method inlined) to tell the framework which method and how is expected to be called). The reason I use "x" for the object in the anonymous method is because it refers to "colaborator" itself so there is no point in adding more names.

The other important difference relates to the "virtual" keyword in C#. Methods in C# are final by default. You can't override them unless they contain the keyword "virtual" on its signature. Both, Mockito and Moq create test doubles by subclassing on runtime, overriding methods and implementing the fake behavior on them (as far as I know). So, if the method you want to stub is not virtual, Moq will throw a runtime exception. If it is not virtual but you don't specify any fake behavior on it, it will not throw exceptions, but worse, it will call the actual implementation. So you might be hiting the database in your unit tests inadvertedly. What I do, is that all my methods are virtual by default (I write "virtual" on their signature).

There will be more posts on this topic :-)

1
Jan

El equipo crece

Buscábamos a un artesano (o lo que a mi me vale por artesano) y hemos tenido la suerte de encontrarle. En enero se incorpora al equipo Ismael Ferrer (@ifolmedo). Tuvimos dos excelentes candidatos, la verdad. Afortunadamente la situación actual de Ismael se alinéa perfectamente con la nuestra. Cada entrevista duró un poco más de una hora. Hubo dos bloques de preguntas teóricas y una sesión de media hora de pair programming. Aquí pongo las preguntas que hicimos. Los dos entrevistados las respondieron todas estupendamente.

Bloque teórico-técnico:

  • ¿En qué consiste el patrón Singleton? ¿Cuándo lo usarías?
  • ¿En qué consiste el patrón Factory? ¿Cuándo lo usarías?
  • ¿Qué es la inyección de dependencias?
  • ¿Qué diferencia hay entre mock y stub?
  • ¿Cómo es el algoritmo TDD?
  • ¿Qué significa SOLID?
  • ¿Por qué motivo harías una clase abstracta?
  • ¿Qué libros técnicos has leido y recomendarías leer?

Bloque sobre habilidades personales (si hizo delante de nuestro tablón kanban):

  • ¿Cómo crees que funciona nuestro panel?
  • ¿Qué información puedes obtener mirandolo?
  • En medio del desarrollo de una tarea que has iniciado, se acerca el dueño de producto y te pide que añadas nuevos requisitos ¿Qué haces?
  • ¿Qué actitud de un compañero te puede llegar a irritar?
  • ¿Qué haces si detectas un conflicto abierto entre dos compañeros tuyos?
  • Un compañero se salta deliberadamente las convenciones y buenas practicas adoptadas en el equipo ¿qué harias?

Muchas gracias a todas las personas que escribieron mostrando interes por venir a hacer la entrevista y sobre todo a las dos personas que al final vinieron.

Ahora continuamos rumbo a la excelencia técnica y de producto. El lanzamiento de producto que hemos hecho esta semana, es el primer salto hacia una nueva etapa de la empresa y del equipo. A por ello!

 

19
Dec

Javascript, an acquired taste

You hate it, you love it

You start hating it but you might end up having so much fun with Javascript. It takes time to acquire the taste and enjoy the powerful capabilities that annoy you at the beginning. This is my experience learning this popular language.
Take into account that my opinion is based on just a few months of experience with Javascript as a language, not just a tool to manipulate the DOM (html and css). It will probably change along the journey.

The white box

Being used to languages like Python, I'd say Javascript is a white-box language while Python is a black-box one. That is, you don't really need to read books to start coding in Python, you just see some example code, try some lines and usually its execution behaves as you expected. It feels so natural. That is not the case of Javascript, its rules are not natural at a first glance. In fact, you have to know very well how the interpreter makes decisions. If you make a mistake writing some code that wouldn't compile or would raise an exception on other programming languages, Javascript will instead try to execute the code. And will probably traverse all the execution path. Because it doesn't fail, this behavior can be very confusing and hard to detect. You wish the interpreter to tell you that, you made a mistake and you probably didn't want to write what you did, you don't want the execution to continue. That is the feeling at the beginning. On the other hand, as time goes by, these capabilities turn out to be so powerful in terms of implementation choices and performance tuning.
Unfortunately coding for performance tuning leads to code that is hard to understand and maintain.

TDD is a must

We've been pairing and test driving our Javascript code these months using Jasmine.  I feel that the impact of BDD on Javascript is bigger than on any other language. It's mandatory. I don't want to write a single line of production code if there is no failing test asking for it. Because Javascript forces me to be smarter than I am sometimes and ocuppies part of my mind with subtle implementation details that moves me away from writing code that expresses the business domain, the semantic of the actual business problem to solve.
If I don't write a test, a specification that clearly states what I expect the code to do and see it pass, I can't bet that it will work just by looking at the production code. It would feel like gambling.

There is a tone of patterns to avoid tipical Javascript mistakes. There are many books on the subject. Experts advise you techniques like, "check the type of the arguments the function receives, to make sure you get what you expect". But then they tell you that "instanceof" operator might not work if the inheritance wasn't implemented properly. It is overwhelming. I tell you a secret... you don't need to master all those patterns if you test drive your code! You don't have to worry about all possible usages of your code if it's you or your team who are going to consume it, because the specifications are already thought, written and are executable.

I always prefer "duck typing" than asking for the type of the arguments. I usually prefer to let Javascript evaluate conditions using its coercion rather than using strict  operators like "===" or "!==". Because if you write code for humans, it is better to say:
"if (userExists)"
than
"if (userExists === true)".

So the approach and the concerns are totally different when you test drive the code. The productivity gain is brutal. Javascript is too expensive to work with if you can't guarantee all the time, that your code functions as you inteded it to be.

If for some reason I would not be able to develop with BDD, I would code with Coffescript rather than Javascript :-)

The approach is totally different if you are writing a framework. Frameworks are too general, they are horizontal, not vertical so there is no business semantic on them. So yes, for frameworks you should be a Javascript power ranger.

OOP or Funtional?

Javascript is not a classical objet oriented language. There are no classes. However is a great language for object oriented programming! Don't be confused with this. If you know the object oriented paradigm, you just need to know how to implement polymorphism, composition and so on. The discussion on "there are no classes, there are prototypes", is superfluous. It is an implementation detail I don't care about. I don't think that is really important because I can express behavior with objects and model the domain the same way I would do it in Java. Rather than using "class" and "extends" I would use "constructor stealing along with prototype chainning". But it's the same tool :-)

On the other hand, javascript is a great language for functional programming too :-) It is actually more used as a functional language than as an OOP one. It is very common to pass functions as parameters and things like that.

You can approach different paradigms with Javascript. My advise is to not mix them together though.

Programming the UI is fun again!

I used to write desktop applications using Delphi, pyGTK and Windows Forms at the beginning of the past decade. When the web started getting mainstream, it was sad to say goodbye to all the best practices learned all those years. Used to the power of event oriented programming, rich components, data binding, and design patterns in general, developing for the web felt a step back. During the past decade there have been many attemps to mimic the old desktop in the web; portlets, asp webforms, and so on. None of them made developers happy, so the Model-View-Controller (MVC) pattern came to the rescue. However, dealing with the UI is still something developer don't really use to enjoy. DOM manipulation has been a pain in the ass with every browser having different behavior and API. I've been trying to avoid it until now and, to be honest, I am happy to not have invested my time fighting with problems that jQuery handles for me nowdays.

Now, ECMAScript 5 is supported in all major browsers. jQuery and other frameworks make life easier. And there is something that we didn't have in the old desktop programming: the chance to programmatically interact with widgets (UI controls or components). Well there are some frameworks for that in the native desktop, by they came late. This means that we can write automated tests for UI behavior!

So now, we have the chance again to use event driven programming, to really implement patterns like the "observer" and many others. And we can test drive all of them!
We can develop semantic components that add domain knowledge inside UI widgets and make the user experience way better. There is no need for intrusive frameworks that tell us exactly all the layers to be used and how. Everything is ready to craft the code to make it express as much human knowledge as possible.

So we are taking the chance.

No need for MVC frameworks

In the first two weeks of the project we started using Backbone. In the first spike, we used the whole framework. A bit later, just the models and collections. Nowdays, we have completely got rid of it. It is a great framework, but we don't need MVC frameworks anymore on the client side because they are more restrictive than we need. We don't develop "screens", we try to create "smart components" that can be reused and provide a different level of abstraction. The screen is just a place holder for components that can be injected. With the rich UI programming that Javascript give us today, the paradigm has changed. It is time to retrieve practices from 15 years ago mixed with best practices learned in the latest years. I wouldn't port or copy exactly what we have been doing recently.

 

13
Dec

RS: enfocados hacia la calidad

Este post de retrospectiva vale por las últimas semanas. Desde el último post de retrospectiva hasta ahora, estamos notando una evolución espectacular en el equipo, tanto en el compromiso que cada uno demuestra escribiendo código de calidad como en la responsabilidad de completar las releases semanales. En la pizarra que usamos en la última reunión de retrospectiva aparecieron más anotaciones positivas que anotaciones de mejora :-)  Sin embargo en este post voy a resaltar lo que queremos lograr.

La cuestión es no parar aquí porque sigue quedando muchisimo camino por recorrer. Simplemente seguir trabajando duro con ayuda de esta sensación de progreso que va calando en el equipo.

Lo que queremos hacer:

  • Los commits aún más cortos y legibles (tengo pendiente un artículo sobre esto que saldrá en la proxima tirada de agilerecord.com). Evitar que los commits lleven diferencias en tabulaciones y espacios para que no se registren cambios que no son de verdad en código sino en configuración del editor de texto.
  • Un branch por feature: tenemos que quitarnos de encima el agobio de que el dia de la subida de versión el branch principal no acaba de estar fino para mezclarlo con estable. Al empezar una nueva funcionalidad iniciaremos un nuevo branch. Cuando se toca código cómun se mezclará con la rama principal y se compartirá para que los demás tengan el cambio disponible lo antes posible.
  • Acelerar la velocidad de nuestras máquinas. En compilar el proyecto (.sln) y lanzar los tests se iba un minuto en cada maquina. Insoportable e impracticable para hacer TDD. Hemos cambiado dos máquinas comprando todo el hardware nuevo, doblando la memoria RAM, y poniendo discos duros nuevos. También hemos optimizado la configuración de la compilación. Ahora se tardan 3 segundos en compilar y otros 3 en pasar los tests. Con eso recuperamos más que de sobra la inversión en hardware. Pero aún quedan varios compañeros con equipos lentos. Es muy importante resolverlo cuanto antes.
  • No hacer cambios en base de datos sin hablarlo primero con los demás y sin que sea totalmente inevitable. Nuestro objetivo es que la BD sea lo último que se toque, tratando de modelar primero el comportamiento en el código.
  • No olvidar pasar todos los tests despues de hacer "merge" y dar la voz de alarma cuando alguno se ha roto.
  • Mejorar el tiempo de respuesta de las incidencias.
  • Seguir formándonos, leyendo libros y practicando ejercicios. En la sesión formativa de los viernes y en casa.
  • Conocer más el código que hacen los demás y la funcionalidad para evitar duplicarla. Tener aún más cuidado en la code review de las mañanas.
  • Automatizar la generación de bases de datos de quita y pon, para pruebas de integración.
  • Cuando el código legado es abrumador, nos trazamos un mini "backlog" de los cambios que queremos conseguir hacerle y una estimacion de tiempos para irlo haciendo (ej: en 15 minutos, cambiar este método para que en lugar de recibir 7 parametros reciba un objeto).

Logros:

  • Aumento de lo concienciado que está el equipo para escribir código más legible y mantenible para los compañeros.
  • Despliegues automáticos. Yeah!!
  • Estamos priorizando mejor. Nadie ha tenido que hacer ni una hora extra porque hemos afrontado a tiempo todas dificultades y la comunicación va mejorando.
  • El número de incidencias va descenciendo.
  • Se están haciendo más commits y más pushes (nos acercamos a la media de 3 commits por hora).
  • Se hace pair programming cuando es productivo y se programa por individual cuando la pareja se da cuenta que no se está aprovechando bien.
Celadon theme by the Themes Boutique
teeth bleaching
baldness treatment