Avoiding null in a controller

Posted by Kevin Burke on Programmers See other posts from Programmers or by Kevin Burke
Published on 2013-06-26T04:02:38Z Indexed on 2013/06/26 4:28 UTC
Read the original article Hit count: 246

Filed under:
|
|

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?

© Programmers or respective owner

Related posts about design-patterns

Related posts about exceptions