Best practices and the joy of programming

lazarus

When I was about 16 years old (1996) I was programming object pascal (Delphi). In that language I wrote a calculator program to convert a number from decimal to binary. While implementing this functionality I found out that I could make this code generic, such that you could give it any base (2 for binary, 8 for octal, 10 for decimal and 16 for hexadecimal) and convert the numbers back and forth. This was an extremely satisfying experience and it felt like I created a thing of beauty, like I discover a secret or maybe as they call it “a programming gem”.

Since nobody uses Delphi anymore (you may want to try Lazarus though), I rewrote the code into Python for any beginner to understand.

def convert_base(s,b,nb):
	# character set
	c = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
	# function to convert int to string
	def int2str(n,b):
		if n==0: return ''
		return int2str(n // b, b) + c[n % b]
	# function to convert string to int
	def str2int(s,b):
		if s=='': return 0
		return str2int(s[:-1],b) * b + c.index(s[-1:])
	# filter invalid characters
	s = ''.join([k for k in s if k in c[0:b]])
	# convert string and return
	if s=='': s = '0'
	s = int2str(str2int(s,b),nb)
	if s=='': s = '0'
	return s

I can’t imagine anyone will feel the same satisfaction reading this code as I did writing it in 1996. Let me explain why. In 1996 we did not have the Internet yet, or Stack Overflow, where all the programming questions you may dream of are already asked. You would typically learn everything from books, both the how and the why, and you could not cut corners by Googling the answer. So there was no guarantee, unlike now, that with proper research you find the most “Pythonic” implementation.

You could even turn this around. Nowadays we know so good how things “should” be done, that there is little room for innovation. If you come up with a different approach to a known problem it quickly dismissed as “wrong” and “not a best practice”. On one hand this may be a sign that the software industry is maturing. On the other hand it may be crippling, because we now have generation of programmers who have no clue why things are the way they are. They can’t argue the motives of their choices any further than it being a “best practice”.

I can think of plenty examples, but the most striking is when I was implementing “default routing” in Symfony2. It is considered a “bad practice” by the Symfony author, hence removed in the second version (and I implemented it again). Hardly any programmer I’ve met can properly argue why it makes sense that it was removed (but they all tend to have an opinion). I guess that proves the point.

Share