Article 693V3 CodeSOD: Magic Strings Attached

CodeSOD: Magic Strings Attached

by
Remy Porter
from The Daily WTF on (#693V3)

Magic strings are as bad as magic numbers, if not worse. So when Tomasz found this block, it didn't seem so bad:

class OPERATION: TRANSACTION = 'conditioned_transaction' BOUNTY_CREATE = 'bounty_create' GUESS_PASSWORD = 'guess_password'

This Python class essentially emulates an enumeration, which while enumerations are now available in Python, it's perfectly plausible that this code predates it and it's fine.

It was after writing this, however, that our intrepid developer lost the plot.

VALID_OPERATIONS = { 'conditioned_transaction': OPERATION.TRANSACTION, 'bounty_create': OPERATION.BOUNTY_CREATE, 'guess_password': OPERATION.GUESS_PASSWORD}

This is a lookup table that maps our handy-dandy enumerated types back to magic strings. Strings which have the same value as the enumerated types. Which ended up getting used like so:

operation = VALID_OPERATIONS[body['operation']]

body is an HTTP request, so this treats the string in the body as a key to lookup the exact same string in VALID_OPERATIONS.

On one hand, we could argue that this is just some premature decoupling- the values in the program don't have to match the values coming from the web request. A little translation table. Which isn't great, but it's not the worst thing.

Except those enumerated values? That dictionary lookup table? These are the only lines on which they're used. Everywhere else in the program, it just sticks with the magic strings.

buildmaster-icon.png [Advertisement] Utilize BuildMaster to release your software with confidence, at the pace your business demands. Download today!
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments