Programming in the small

Some people are interested in the big problems of programming - enterprise architectures and the like. Other people are interested in the medium size problems - design patterns, which framework to choose for testing, how to organise programming teams. I am interested in both of the above, but I am especially interested in a problem at an even lower level. How do we write code that is easy to understand, easy to maintain and robust.

I am not talking about things like test driven development, peer reviews and change management. All these things happen at a higher level. I am interested in what the code looks like. I will lead with a simple example. Suppose we have an attribute which has a default value. For example, we allow the user to specify a ‘repeat’ value (whatever that is), but if they don’t provide one, we will default to zero.

In Python, the code may look like this:

if len(argv) > 1:
    repeat = int(argv[1])
else:
    repeat = 1

This code works, but is it the cleanest code we can write? I believe that the following code is clearer:

repeat = 1
if len(argv) > 1:
    repeat = int(argv[1])

Firstly, it is only three lines. This does not necessarily make it clearer or more maintainable. However, looking at the code, it is easy to see that the variable repeat is always initialised. We don’t have to think our way through both use-cases (i.e. what if argv is less than 2).

An argument against the second case would be that in the case where the user has supplied a value, two assignments are done to repeat. Some people may consider this an issue. I think that the benefit from the readability outweighs the costs of the two assignments.

Finally, some languages offer a single line ternary operator. Is this clearer:

repeat = argv[1] if len(argv) > 1 else 1

While this is even shorter than the previous code, I am not convinced that it is more readable, maintainable and robust.