Thursday, 25 March 2010

You duplicating? You wrong…

This is not the best example for the issue, but here we go: imagine your are going to sweep your house, and that you have one of those modern brooms that can be disassembled to fit into small broom cupboards. When you start, let’s say in the kitchen, you take the broom from the cupboard, assemble it, and start sweeping. When you are done with the kitchen, you don’t disassemble it and place it into the cupboard, because you have other rooms left, do you? You would feel stupid assembling and disassembling the broom for each room, wouldn’t you?
Then why you do that when you write software?

First, some misprints of the writer

Thanks to M. Barnett for pointing out the “mounting and dismounting broom” issue. It seems that I wrote this post too fast (or too late), and I didn’t notice that “mounting a broom”, in English is more something like this:

So I changed it to “assemble” and “disassemble” which is what I meant to write the first time, I promise… ;)


This post is about some very basic thoughts, about engineering behaviors students tend to forget… It might sound obvious for experienced people, so if you are one of them, better go get a beer with friends instead of reading it. So, back to what students forget. Among others, one of the most important things to keep in mind, one that will always guide you through the right path is:
And this applies not only to software development, but also to content management, organization and engineering in general. Damn! it even applies when you tiny up a wardrobe or clean the kitchen, as we saw in the preface.

Why is this misbehavior so usual in software?

Easy. Assembling a broom and taking it to the cupboard takes time, and therefore it is trivial for any dumb-ass to see that’s a waste of time. In software, many times it takes less time duplicating things than thinking how to avoid the duplication. It’s just a matter of Copy-Paste, when avoiding duplication can take weeks of work. That’s why duplication appears all around in bad software.

The student counter part

At this point, it’s when students tend to say:
- <<Weeks! then it is indeed better to duplicate code than loosing weeks>>
And then you play the role of the old, wise grandpa, telling them:
- <<Believe me, it’s better this way. You will thank it, when you grow older…>>

Example 1: Duplication of work - Duplication of decisions

Chronicles of a bad developer

  • Company “A”
  • Project “B”
  • You are the “Bad developer #1”
  • A simple operation: obtain the concatenated name of a user, composed as: “Name” + “Second Name” + “Last Name”
It’s just one line of code, so you come to the conclusion that it’s not worthy to think much about it. So, you leave it like that and copy-paste the line when you need it.
Some months later, project “B” has grown, becoming “big”, with let’s say 150 sub-projects. Your famous name composition operation is scattered all around, in more than 1500 places. Now imagine that the worst happens (the worst always happens), and that your boss demands a change in the way you are concatenating names. Let’s say, he wants it in the form: “Last Name, First Name”, instead of the previous. You are screwed, easy as that.
As you are a bad bad developer, first thing you say is:
- <<Boss, are you sure we need that change? I like names in the way they are right now>>
- <<Our clients don’t>> He replies…
No prob, you are a bad, but clever developer, so you think:
- <<Visual Studio will fix this, I heard somewhere that there’s a thing for these cases called Refactoring>>
Then you try to Refactor a whole sentence, and of course, it doesn’t work.
- <<Damn Visual Studio! Damn Microsoft! For things like these is why I prefer Linux! Sure that Linux knows how to Refactor a whole sentence>>
And then, you end up making massive text replacements, investing one week trying to find all the instances of the operation, and in fixing the resulting compilation errors. Of course, you forget to change 3 or 4 instances of it. That’s when you go to your boss again and say:
- <<Hey, not that bad. 3 out of 1500, that’s a 99% of success!>> 
- <<You are a 99% of an idiot>>… He replies…

Diary of the good developer

<<Monday, 36 of October of year 2124
Today, I slept well. I had breakfast and went to the office. My job for today was changing the way names are concatenated in our software. As I was clever enough a couple of months ago, and I isolated this task inside a method, all my job for today has been done in 10 secs. The rest of the day I was in the beach, getting some sun… No phone calls from my boss. No phone calls from clients… No news is good news. Life is wonderful…>>
You learned the lecture?

What lecture?

Pay attention Padawan to the following line of code:
FullName = Name + SecondName + LastName;
It doesn’t only make a name composition. It also decides how this concatenation will be done, and this is the key point. That’s what you need to understand and learn. Because duplicating work is bad, but duplicating decisions is one of the worst things you can ever do in software. I´ll put that in big so you remember it:
Remember: Duplicating work is bad, but duplicating decisions is one of the worst things you can ever do in software

Example 2: Duplication of Contents

As we mentioned, duplication is not only a software development issue.
Copy-pasting files is slower than copy-pasting code, but for sure it’s still faster than assembling and disassembling the broom ;)
That’s why many dumb-asses still don’t get it, making duplication of contents to be pretty frequent too. It’s the same stuff. You make a texture, you use it in hundreds of 3D models, and then one day you need to change it. You are screwed again man!
How to avoid duplication in this cases?
You should think about having global repositories for contents that are shared between many entities: texts, textures, sounds, xml files, whatever. Remember, duplication is the source of all evil in the world. If you find yourself doing a Copy-Paste, ask yourself if it is really necessary or if there’s a way to avoid it.

Example 3: Other, not so obvious, forms of Duplications

Imagine we have a game with the class Player, and with a property which holds his status. You know, things like “Dead”, “Alive”, “Running”, etc. At design time, we need to choose how to store that status:
  • The core C++ kings that want his player to be dead and alive at the same time (may be a zombies game?), will want his status to be an Hexadecimal Flag
  • Those who want their game to be fast and “cross-platform with their toaster”, will want his status to be an Int, you know: 0, 1, 2, etc
  • A Visual Basic developer will probably want it to be a String, actually writing the value “Dead”, “Alive”, etc.
Anyone is right? Nope (unless special circumstances). Let’s debate

Speed vs Comprehensiveness

- << Who said to use strings? Oh yes, the VisualBasic people… Come on man, do you know how slow is to compare two strings? Player is a core class, that is used all along the game, even in performance critical parts. You cannot be serious… strings… The solution is to use an Int, or an Hex flag.>>
- <<Who said to use an Int or an Hex Flag? Of course! The native people. Why not we all just turn back into binary, you prehistoric monkeys? Will we need to check what “State = 0” is every time we need to use it?  Man you cannot be serious… ints… The solution is to use strings…>>
As you probably already notice, one can stay like that forever, when there’s a much better solution… Yes, you clever boy, we will use Enumerations. But, do you know why? And what is more important, are you aware of all the benefits (and cons) of an Enumeration? Will talk more on this later, by now lets get deeper in the cons of the other alternatives.

Anyone said duplication again?

We have seen duplication of work (bad), and duplication of decisions (very bad). What none of the contenders in the previous discussion have seen is that both solutions imply a new, hidden form of duplication. It’s what I call: duplication of abilities.

Duplication of Abilities (also very bad)

When you choose to store the status of your player as an Int, or as a String, with values like “Dead” or “Alive”, you are delegating in all your developers the responsibility of writing that values correctly. In other words, you are duplicating the need for the ability to write it correctly in many many different places, and by many different people, instead of centralizing in a single point.
It’s quite likely that, from time to time, someone makes a mistake. So if any of them misspells a string value (“Deaz” instead of “Dead”), or simply misplaces an int, writing “1” instead of “0”, the compilator won’t say a thing, and the application will seem to run just fine. But... What are the effects of setting the status of a player incorrectly in a single, deep point of your code? Absolutely unpredictable. That can manifest as any kind of error in the application, what makes it very difficult to debug, trace and fix.
You must try to avoid this kind of duplication too, centralizing decisions, and reducing the number of places where a mistake can be made. 

Strong-type, baby

We said it before, but let’s just analyze another alternative for storing the “State” of the player in our game. What about Enums?
  • Enums are as fast at runtime as an Int or an hex flag
  • Enums are as comprehensible as Strings at debug time
  • Enums are convertible to and form Int, what makes cross-platform easy
  • Enums are convertible to and from String, what makes printing information easy
  • Enums are much more confortable to use, thanks to the Intellisense, you don´t need to remember the values, nor type them, just select them on the list
  • Enums are strongly typed, which will:
    • Minimize the so-called Duplication of Abilities. Since you select values on a list (thanks to the Intellisense) instead of typing them, you centralize the responsibility of making no mistakes in the enumeration
    • Even if any one ignores the Intellisense, and types the values manually, the presence of “hard to find” errors is also minimized, as a miswritten Enum value will be detected at compilation
So, YES! Enums ROCK! And thanks to the static helper methods found in the .Net Framework (Enum.Parse, Enum.GetNames, Enum.GetUnderlyingType, Enum.GetValues, Enum.IsDefined, etc), they are very versatile too.
So… Use them!!!

An additional security shield

Even if you are already strong-typing, there’s another thing you should always do, specially in big projects that cannot be tested completely too frequently… exactly, that’s correct: UNIT TESTING.
Again, designing good unit tests can take weeks, and again, students will say: <<Weeks! The it’s better not to use unit tests>>, and again you will have to tell no no no…
Unit test are the definitive way for giving big projects the robustness they need, going into places where the compiler can’t go, and testing deeper that just syntax. A unit test can detect a wrong player State, but of course, it has to be well designed. If you want to know more about unit testing, please refer to the following article by Roy Osherove:


Every time you find yourself doing a Copy-Paste, ask yourself:
  • Why are you doing it
  • Is it really necessary to duplicate what you are duplicating
  • Can it come to problems if something changes in the future
  • Is there any way of avoiding that duplication
Try to find implicit or hidden duplications, that can be problematic in the future. Try to reduce the number of places where mistakes can be made. Try to reduce the number of people that can make mistakes (and I mean something deeper than firing dumb-asses!). Strong-type and Unit-Test when possible!
Finally, apply some common sense to all of this. Sometimes, you should do just the opposite to what I´m telling… ja ja… ;)
Take Care!

Wednesday, 17 March 2010

Historial de llamadas a revisión… a merced de los medios

Recalls, Recalls, Recalls: Where Does Toyota's Problem Rank In The History Of Famous Recalls?Mucho se está hablando últimamente de los problemas de Toyota y otras marcas/grupos como Honda, GM, Ford, etc con llamadas a revisión masivas. A la gente le da bastante miedo que su coche, por voluntad propia, se lance cual kamikaze contra la pared, o se queme “a lo Bonzo” sin motivo aparente. Esto es una prueba más, de que somos (todos, y me incluyo) unos borregos, a merced de lo que diga nuestro nuevo Dios (TV, media, prensa, llámalo como quieras…).

Llamadas a revisión ha habido muchas, siempre. Y ni son una medida de la calidad de producto de una marca, ni deben ser utilizadas como arma arrojadiza. Además, hacer comparaciones como se están haciendo es muy complicado porque… ¿en qué términos o bajo qué patrones comparamos? Unas marcas venden mucho más que otras, por lo que es normal que una llamada a revisión en GM implique a muchísimos más coches que otra en Subaru.

Aun así, como ahora los medios no deben de tener mucho contenido, o a alguien (he oído GM o Ford?) le interesa desviar la atención sobre sus propios defectos, (por lo visto que los adelantaran como primer productor mundial les hizo mucha pupa), pues nada, a llenar páginas y páginas poniendo a caer de un guindo a Toyota, Honda y compañía.

¡Qué difícil es conseguir que la gente se informe un poco!

En fin, estoy de acuerdo en que las llamadas a revisión son preocupantes y generan alarma, pero démonos cuenta de que están siendo utilizadas como medio de desprestigio masivo. Todos sabemos que no importa si ya se ha demostrado o no, que X personas murieran como consecuencia del defecto Y del coche Z. Muchas llamadas a revisión son PREVENTIVAS, y aunque dicho defecto nunca se haya manifestado en la práctica, y nadie haya sufrido sus consecuencias, el mal ya está hecho: las ventas de dicha marca caerán en picado.

Y no pretendo decir que no haya habido llamadas a revisión muy serias últimamente (y siempre). Muchas marcas juegan a esto del desprestigio (no todas, hay algunas más elegantes que otras), pero lo que está pasando últimamente con Toyota ya me parece de escándalo, máxime cuando son las marcas y medios Americanos las que más se están cebando con las Europeas o Japonesas. ¡Es de coña! Al final va a resultar que un Dodge tiene más calidad y/o tecnología que un Toyota, un BMW o un Volkswagen…

Así que nada, me parece que la única forma de tratar de arrojar luz sobre este tema es recopilar algunas estadísticas de diferentes fuentes. Es importante recalcar que muchas de estas fuentes son Americanas, así que nadie se lance cual Halcón Milenario a mi cuello tildándome de anti-GM o anti-Ford.

Para abrir boca -Las diez mayores llamadas a revisión de la historia Estadounidense-

Esta lista es muy subjetiva, y no tiene mucho valor probatorio de nada, porque clasifica las llamadas a revisión por número de coches afectados. Obviamente, aquí no aparecen marcas pequeñas (si vendes poco, no puedes hacer llamadas a revisión masivas), y además no tiene en cuenta la fecha. Quiero pensar, que no es lo mismo una llamada a revisión de 1970 que una de 2009. Aún así, resulta interesante revisarla:

  • 1st place: Ford, 2008-09 (14.1 million). Peligro de fuego eléctrico por un fallo en el Cruise Control
  • 2nd place: Ford, 1996 (7.9 million). Fallo en el sistema de ignición.
  • 3rd place: GM, 1971 (6.7 million). Sujeciones de motor que se soltaban. El motor caía sobre el cable del acelerador, provocando aceleración máxima en el vehículo
  • 4th place: GM, 1981 (5.8 million). Suspensiones inestables que podían poner en peligro la estabilidad del coche
  • 5th place: Ford, 1972 (4.1 million). Cinturones de seguridad defectuosos que se desenganchaban
  • 6th place: Toyota, 2009 (3.8 million). Alfombrillas defectuosas que podían llegar a atascar el pedal del acelerador (en posición de aceleración)
  • 7 – 9th place: GM, 1973 (3.7 million). Volantes que dejaban de funcionar (no se podía guiar el vehículo)
  • 7 – 9th place: Honda, 1995 (3.7 million). Cinturones de seguridad que se soltaban solos, o que no se soltaban tras un accidente, dejando a la víctima atrapada.
  • 7 – 9th place: Volkswagen, 1972 (3.7 million): A los Beetles se les caían los limpia-parabrisas…
  • 10th position: GM, 2004 (3.6 million): 1999 and 2004, 134 people received minor injuries

¿Vemos quién se lleva la palma no? ¿Por qué entonces en U.S. solo se habla de Toyota? ¿Será porque en los últimos años le comió el pan del morral a G.M. y a Ford?

Llamadas a revisión más importantes en los años 2009 y 2010. Fuente: aqui

Se han eliminado aquellas repetidas, o que implican a un bajo número de vehículos (menos de 50.000). Algunas entradas no especifican número exacto de unidades, sino modelos y “añadas” (ej: BMW Serie 3, años 2007 y 2008). Es de suponer que este último modo implica también muchas unidades, y suponemos que entre éstas estará la llamada masiva de Ford de 14 millones de unidades descrita en la parte anterior.

Mar 2010

Feb 2010

Jan 2010

Dec 2009

Nov 2009

Oct 2009

Sep 2009

Llamadas a revisión más importantes en los años 2007-2009


Según esa fuente, y si no he contado mal, entre 2007 y la actualidad, estos han sido los números de llamadas a revisión importantes (de más de 50.000 uds, o afectando a uno o varios modelos de uno o varios años), por marcas o grupos:

  • General Motors: 11
  • Ford: 8
  • Nissan: 8
  • Chrysler: 7
  • Volkswagen: 4
  • Honda: 4
  • Toyota: 4
  • Hyundai: 3
  • BMW: 2
  • Dodge: 1
  • Subaru: 1
  • Mercedes: 1

Conclusiones y cosas a tener en cuenta

  1. Todas, y digo TODAS, las marcas llaman a revisión a vehículos. A todas les ha llovido mierda alguna vez, así que ojito con acusar de formas tan vehementes…
  2. Muchas llamadas a revisión son preventivas, así que el hecho de que una marca haga muchas, puede implicar 2 cosas: o tienen mala calidad y la cagan a menudo, o es una marca con gran transparencia y buena respuesta y previsión. En algunos casos será la primera opción, en otros la segunda, y en otros un poco de todo. Tú elijes con cual te quedas.
  3. No todas las llamadas a revisión son iguales. No es lo mismo una cerradura que pierde aceite y mancha la carrocería, que un airbag que no salta, ¿no crees? Para utilizar las llamadas a revisión como arma arrojadiza, y tan a la ligera como algunos medios las están utilizando, habría que hacer un estudio muy muy profundo de la seriedad de los defectos, sus consecuencias, y lo que es más importante: la velocidad a la que fueron detectados, la respuesta que dio la marca para subsanarlos y las consecuencias que tuvieron.

Así que ya sabes, no midas la calidad de una marca solo por el número de llamadas a revisión que hace, infórmate y no te dejes influenciar ni engañar por los medios. Ni a favor ni en contra de nadie.

Un coche se compone de miles y miles de piezas móviles, fabricadas por decenas de empresas diferentes, sometidas a grandes esfuerzos, y que pueden funcionar sin parar durante miles de kilómetros. Demasiado bien funcionan, ¿no crees?

Referencias y más información

Si deseas saber más, google te echará una mano. Aquí tienes algunos links directos:

Friday, 5 March 2010

Arf arf arf…. ¡quiero uno! Toyota FT-86

Últimamente vamos de enamoramientos por aquí… y aquí llega uno más… ¡No puedo esperar a que lo saquen a la venta!

Que si se llamará Supra, que si se llamará Celica, que si otros lo llaman Tobaru (Toyota + Subaru)… da igual. Se llame como se llame, este buga me pone los pelillos como picos de escarpias… Tracción trasera, diseño Europeo, compact-coupé acojonante, motoraco (esperemos que sobradamente por encima de los 200 cv, viendo la última escalada de potencias en los compactos) y encima asequible… Salivo solo de pensarlo.

Fotos fotos…





Y aquí con sus ancestros…


Estos coches (igual que los de la gama M de BMW, o la gama S de audi, o la gama AMG de Mercedes) quizá no sean los más rentables de las marcas, pero sin duda ayudan (y mucho) a su imagen y al final, hacen que se vendan muchos más Auris, Avensis, o IQs.

Si señor, Toyota, así se hace…

Wednesday, 3 March 2010

¡Hay por dios, qué cosa más bonita! Pininfarina + Alfa presentan en Ginebra el 2uettottanta

Iba a tratar de decir algo, pero me he dado cuenta de que en este post solo debe haber fotos. Fuente: autoblog

pininfarina-17-1[1] pininfarina-3[1]pininfarina-21[1]

03-pininfarina-alfa[1] 02-pininfarina-alfa[1] 06-pininfarina-alfa[1]