Friday, May 30, 2008

Don't assume your data is valid

I've come to think that you should never code with the assumption that your data is valid. Now that doesn't mean that you're going to get the desired result if your data is invalid, maybe you just don't have what you need. But your code should try and do as much as it can with as little as possible.

For example, if you have a rails controller that returns a collection, don't let an exception accessing one of those objects prevent the entire list from returning. If you have a shopping cart and heaven forbid, you code finds an object that doesn't pass validations but is nonetheless persisted in the database, don't return an error page, log the issue and return a partial list and telling the user that an error occurred and some items had to be removed from their basket.

This has applications in large scale applications too, where maybe you don't have a strict database schema or you can't run migrations on your entire dataset everytime you make a code change. Your code is going to receive data that is out of date, incomplete, incorrectly formatted, or just plain broken. Take any data your code receives, don't make any assumptions and do the best you can. Your program will be more flexible, more resilient, and it will be more likely when an major error occurs that the user will be able to continue in some way.

No comments: