Mis cachivaches para trabajar


Siempre hay un cierto interés por conocer el equipo y programas que otros desarrolladores usan para trabajar. Ya que uso ciertas cosas “raras” (al menos poco frecuentes) y tras escuchar el último podcast de “El amuleto de Yendor”, que comentaban algunos de estos temas (especialmente teclados).

Como introducción, me dedico principalmente a programar en Python, así que el entorno está adaptado a eso. Como este post está quedado muy largo, empiezo con el hardware (ordenador, trackball, configuración de teclado y teclados) y continuaremos en otro post con el software.

Ordenador

Desde hace un par de años uso, tanto en el trabajo como en casa, ordenadores Mac.

iMac

Mira que es bonito el puñetero

Tengo un iMac de 27” que funciona muy bien. Me encanta la pantalla, tiene una resolución fantástica y, la primera vez que lo utilicé, me impresionaba lo grande que era.

Antes de eso utilizaba Ubuntu. Desde hace tres años no utilizo Windows y no tengo ganas de volver, la verdad. Tuve una muy mala experiencia (instalando un Service Pack me borró TODO el disco duro) y, para el tipo de cosas que lo uso, no lo echo de menos. NO, no echo de menos los juegos. No tengo consola y soy de  jugar juegos tipo Flash o en el iPad. A pesar de trabajar en la industria del videojuego, no soy un gran “jugón”.

Me gusta el hecho de que sean máquinas Unix, de manera que puedo programar con relativa facilidad software que luego correrá en servidores Linux y poder utilizar software libre del entorno. Utilizo Mac Ports para instalar muchas herramientas de código abierto, aunque tiene sus problemas. En mi caso utilizo mucho la línea de comandos para programar, pero el interfaz es muy bonito para las tareas fuera de eso.

Continue reading

Think a little about the readers of your web site


This is a translation of a post by Ricardo Galli about some of the lessons he has learned on Menéame, a social news website in Spanish similar to Digg. I wanted to share some of the concepts with my co-workers, but I thought that it could be interesting to translate the complete work and share it with the whole world ;-) Any English errors are my own. I will also like to thank David Brodigan for help me reviewing the English version.

Bored of having to wait more than 5 seconds to display a blog’s page? Annoyed with those sites with dozens of widgets, gadgets, AJAX effects and mashups that take hours to load? Troubled because you have developed a very efficient program for the last hot framework and “it’s slow”? Me too, and that worries me a lot, These sites are incredibly crap pieces of work that don’t take into account the basics about usability and human interface: Response time perceived by the user.

You can criticize everything else about Menéame, except its speed or that we have not taken into account this very important aspect, that’s why I’m sharing the few rules we have been following very strictly. We already knew some, but we have also learnt many more during these past five years of development .

There are a lot of parameters to take into account to develop “fast” websites. Not only the server speeds, or the time it takes the server to generate dynamic HTML, there are other parameters that directly affect the browser and user’s perception.

In July 2001 I wrote an article at Bulma [in Spanish] where I explained, according to measurements made during the development of the first sites of Diari de Balears and Última Hora (during the years 1997-1998), the fundamental technical parameters to measure and take into account: response time, return time, download time and “display time”. That last parameter, display, is the one that has the most impact for the user. The user expects a quick response, and that’s mostly perceived as the time that takes for the page to start to display on the browser.

Continue reading

Commenting the code


please_explainI always find surprising to find out comments like that regarding code comment. I can understand that someone argues about that writing comments on the code is boring, or that you forget about it or whatever. But to say that the code shouldn’t be commented at all looks a little dangerous to me.

That doesn’t mean that you’ll have to comment everything. Or that adding a comment it’s an excuse to not be clear directly on the code, or the comment should be repeat what is on the code. You’ll have to keep a balance, and I agree that it’s something difficult and everyone can have their opinion about when to comment and when not.

Also, each language has it’s own “comment flow”, and definitively you’ll make more comments on low level languages like C than in a higher level language like Python, as the language it’s more descriptive and readable. Ohhh, you have to comment so many things in C if you want to be able to understand what a function does it in less that a couple of days… (the declaration of variables, for example) #

As everyone has their own style when it comes to commenting, I’m going to describe some of my personal habits commenting the code to open the discussion and compare with your opinions (and some example Python code):

    • I put comments summarizing code blocks. That way, when I have to localize a specific section of the code, I can go faster reading the comments and ignoring the code until getting to the relevant part. I also tend to mark those blocks with newlines.
# Obtain the list of elements from the DB
.... [some lines of code]

# Filter and aggregate the list to obtain the statistics
...  [some lines of code]

UPDATED: Some clarification here, as I think that probably I have choose the wrong example. Of course, if blocks of code gets more than a few lines and/or are used in more than one place, will need a function (and a function should ALWAYS get a docstring/comment/whatever) . But some times, I think that a function is not needed, but a clarification is good to know quickly what that code is about. The original example will remain to show my disgrace, but maybe this other example (I have copy-paste some code I am working right now and change a couple of things)
It’s probably not the most clean code in the world, and that’s why I have to comment it. Latter on, maybe I will refactor it (or not, depending on the time).

               # Some code obtaining elements from a web request ....

                # Delete existing layers and requisites
                update = Update.all().filter(Update.item == update).one()
                UpdateLayer.all().filter(UpdateLayer.update_id == update.item_id).delete()
                ItemRequisite.all().filter(ItemRequisite.item == update).delete()

                # Create the new ones
                for key, value in request.params.items():
                    if key == 'layers':
                        slayer = Layer.all().filter(Layer.layer_number == int(value)).one()
                        new_up_lay = UpdateLayer(update=update, layer=slayer)
                        new_up_lay.save()
                    if key == 'requisites':
                        req = ShopItem.all().filter(ShopItem.internal_name == value).one()
                        new_req = ShopItemRequisite(item=update, requisite=req)
                        new_req.save()
  • I describe briefly every non-trivial operation, specially mathematical properties or “clever tricks”. Optimization features usually needs some extra description telling why a particular technique is used (and how it’s used).
# Store found primes to increase performance through memoization
# Also, store first primes
found_primes = [2,3]

def prime(number):
    ''' Find recursively if the number is a prime. Returns True or False'''

    # Check on memoized results
    if number in found_primes:
        return True

    # By definition, 1 is not prime
    if number == 1:
        return False

    # Any even number is not prime (except 2, checked before)
    if number % 2 == 0:
        return False

    # Divide the number between all their lower prime numbers (excluding 2)
    # Use this function recursively
    lower_primes = (i for i in xrange(3,number,2) if prime(i))
    if any(p for p in lower_primes if number % p == 0) :
        return False

    # The number is not divisible, it's a prime number
    # Store to memoize
    found_primes.append(number)
    return True

(Dealing with prime numbers is something that deserves lots of comments!) EDIT: As stated by Álvaro, 1 is not prime. Code updated.

  • I put TODOs, caveats and any indication of further work, planned or possible.
# TODO: Change the hardcoded IP with a dynamic import from the config file on production.
...
# TODO: The decision about which one to use is based only on getting the shorter one. Maybe a more complex algorithm has to be implemented?
...
# Careful here! We are assuming that the DB is MySQL. If not, this code will probably not work.
...

UPDATE: That is probably also related to the tools I use. S.Lott talks about Sphinx notations, which is even better. I use Eclipse to evelop, which takes automatically any “TODO” on the code and make a list with them. I find myself more and more using “ack-grep” for that, curiously…

    • I try to comment structures as soon as they have more than a couple of elements. For example, in Python I make extensive use of lists/dictionaries to initialize static parameters in table-like format, so use a comment as header to describe the elements.
# Init params in format: param_name, value
init_params = (('origin_ip','123.123.123.123'),
               ('destiny_ip','456.456.456.456'),
               ('timeout',5000),
              )
for param_name, value in init_params:
    store_param(param_name, value)
  • Size of the comment is important, it should be short, but clearness goes first. So, I try to avoid shorting words or using acronyms (unless widely used). Multiline comments are welcome, but I try to avoid them as much as possible.
  • Finally, when in doubt, comment. If at any point I have the slightest suspicious that I’m going to spend more than 30 seconds understanding a piece of code, I put a comment. I can always remove it later the next time I read that code and see that is clear enough (which I do a lot of times). Being both bad, I prefer one non-necessary comment than lacking one necessary one.
  • I think I tend to comment sightly more than other fellow programmers. That’s just a particular, completely unmeasured impression.

What are your ideas about the use of comments?

UPDATE: Wow, I have a reference on S.Lott blog, a REALLY good blog that every developer should follow. That’s an honor, even if he disagrees with me on half the post ;-)

On one of my first projects on C, we follow a quality standard that requires us that 30% of the code lines (not blank ones) should be comments.