Code that sucks
Every programmer has seen code that sucks. I’m not claiming I’m the best, but I’ve been noticing more and more of other people’s code that just is crap, which says to me that if I can make that distinction, then I know what I’m doing.
Compare this routine, which takes a list of strings and pretty-formats them with commas and an ‘and’ before the last element:
def printableRoles(roles):
'''Takes a list of role strings and returns a nice string for printing in messages'''
print_roles = ''
for i, role in enumerate(roles):
if i != 0:
if i != len(roles)-1:
print_roles += ', ' + role
else:
print_roles += ' and ' + role
else:
print_roles += role
return print_roles
with what I replaced it with:
def printableRoles(roles):
'''Takes a list of role strings and returns a nice string for printing in messages'''
if not roles: return ''
if len(roles) == 1: return roles[0]
s = ', '.join(roles[:-1])
s = ' and '.join([s, roles[-1]])
return s
I’d love to see any shorter versions. There might even be a routine in one of python’s modules for this, in which case the next guy maintaining this code will have the same opinion of me as I do of the first implementor.