Avoiding null in a controller
- by Kevin Burke
I'm trying to work through how to write this code.
def get(params):
""" Fetch a user's details, or 404 """
user = User.fetch_by_id(params['id'])
if not user:
abort(404)
# Render some template for the user...
What's the best way to handle the case where the lookup fails? One principle says you should avoid returning null values from functions. These lead to mistakes and AttributeErrors etc. later on in the file.
Another idea is to have fetch_by_id raise a ValueError or similar if no user exists with that id. However there's a general principle that you shouldn't use exceptions for control flow, either, which doesn't help much.
What could be done better in this case?