The wrong way to use asserts

One of the ways programmers use to help ensure that inputs to methods are correct is to use asserts. Basically these will test conditions and stop execution if a test fails. By default, Xcode suppresses these asserts in release builds so that the code will simply continue.

This past weekend, I was helping out on a project and found that the app stopped because of an assert indicating that a condition was not satisfied. As I looked into it closer, the programmer had put in asserts to test the results of what came back from the server. The author then didn’t do runtime checks to validate the data, he simply assumed that if the assert passed, that the data was valid and continued. The problem is that, in this case, the server returned data that the code wasn’t expecting, so in a release build, the code would have continued and then crashed because the data wasn’t in the correct format.

While I’m not a huge fan of asserts, they do have their place, just not here. The code should have done runtime checks and gracefully handle bad server data.

I suspect that the author hadn’t done enough client-server communication to know that servers return bad data more often than you’d expect. I’ve worked on so many projects where a simple server change causes clients to have hiccups, that I’ve gotten pretty good at defensively programming against this.

If you choose to use asserts, make sure that you also use runtime checks and gracefully handle conditions that you test for in the asserts as the asserts go away in release builds.

2 Replies to “The wrong way to use asserts”

  1. One thing we’ve done lately is that whenever the server returns bad data, we in turn bundle up the URL and data and post it to another server. We immediately know when there’s a problem that way.

    1. One of my co-workers was suggesting that yesterday. We just need to create a service to handle that data. However, except during development, are you really going to look at the data?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.