Ian S was going through the portfolio of applications maintained by his company, and stumbled across one that… well, from what he could tell, wasn’t written by a developer so much as spawned by an accident. 90% of the code was copy-pasted from somewhere else in the code, flow-of-control mostly used Exceptions as an attempt at doing GOTO-style logic, and there were piles of unused variables or variables used before initialization. Some modules/packages in the application were full of syntax errors, which implied that they weren’t actually included or used anywhere.

From that mess, Ian extracted this.

while True:
   try:
       product.save (force_insert=True)
   except:
       pass

   if Product.objects.filter(version=pv,productType=pt).count() is not 0:
       break
   time.sleep (1)

This is Django, which means we’re looking at some ORM-based code. First, we try and save a product object into the database. If that fails for any reason… we ignore that failure. Instead, we check to see if there are any products with the same version/type combination- I’m going to go out on a limb and guess that this is the unique identifier of the product, but I wouldn’t put down money on it- and if there is at least one entity that matches… we break out of the infinite loop.

If, on the other hand, there isn’t- that means that we failed to insert the product. So let’s just wait a second and then try again. And again. And again. And…

There are a million better ways to write this, but I’m honestly impressed by the determination this code shows. It doesn’t give up. It never gives up. It will insert that record, or die trying. That’s how winning is done.

[Advertisement] Utilize BuildMaster to release your software with confidence, at the pace your business demands. Download today!