Your function parameters should be as simple as possible

By | February 22, 2016

Let’s say you have a function to process a GET parameter from a HTTP request, the bad example to do this is:

def process(request):
    value = request.GET.get('name')
    work(value)

process(request)

The above example has 2 problems:
1. This will become a nightmare to write unit tests on this function, now you need to mock the request object to contain the attribute GET which is a dictionary has a key ‘name’
2. Person reading the code has to spend the effort of what other usage of “request” in the function.

The proper way is to accept a parameter as shallow as possible, in this case, a string

def process(value):
    work(value)

process(request.GET.get('value'))

The above example has 2 advantages:
1. Easy to write unit tests, all you need now is pass in a string
2. The person reading the calling statement knows a string is passed in, no other values are involved.

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.