CodeSOD: Assertive Programming
Defensive programming is an important tool in any developer's toolbox. In strictly typed languages, types themselves provide a natural defense against certain classes of bugs, but in loosely typed languages, you may have to be more clear about your assumptions.
For example, in Python, you might choose to use the assert keyword to, well, assert that something is true. It's often used in debugging, but it's also a good way to ensure that the state of the parameters passed to a function, or some other state of your system is correct before doing anything else. If it's not, the code raises an exception.
Dima R found this "interesting" riff on that concept.
try: assert r.status_code == 201 except: print(r.text) pass
Here, the assertion is confirming that we get the expected HTTP status code from a request, but if we didn't, it doesn't bubble up the exception- it just prints the body of the response.
This code has been in production for some time. When Dima tracked down the culprit and asked what they were thinking, the developer admitted:
[Advertisement] Utilize BuildMaster to release your software with confidence, at the pace your business demands. Download today!it was originally an assert just for sanity, but then I wanted to print the result if the assert failed and I wasn't paying very much attention lol