9. WRITING EFFECTIVE FUNCTIONS

Functions are like mini programs within our programs that allow us to break code into smaller units. This spares us from hav- ing to write duplicate code, which can intro- duce bugs. But writing effective functions requires making many decisions about naming, size, param- eters, and complexity.

This chapter explores the different ways we can write functions and the benefits and drawbacks of different trade-offs. We’ll delve into how to trade off between small and large functions, how the number of parameters affects the function’s complexity, and how to write functions with variable numbers of arguments using the * and ** operators. We’ll also explore the functional programming paradigm and the benefits of writing functions according to this paradigm.

Function Names

Function names should follow the same convention we use for identifiers in general, as described in Chapter 4. But they should usually include a verb, because functions typically perform some action. You might also include a noun to describe the thing being acted on. For example, the names refreshConnection() , setPassword() , and extract_version() clarify what the function does and to what.

You might not need a noun for methods that are part of a class or mod- ule. A reset() method in a SatelliteConnection class or an open() function in the webbrowser module already provides the necessary context. You can tell that a satellite connection is the item being reset and that a web browser is the item being opened.

It’s better to use long, descriptive names rather than an acronym or a name that’s too short. A mathematician might immediately understand that a function named gcd() returns the greatest common denominator of two numbers, but everyone else would find getGreatestCommonDenominator() more informative.

Remember not to use any of Python’s built-in function or module names, such as all , any , date , email , file , format , hash , id , input , list , min , max , object , open , random , set , str , sum , test , and type .