Function arguments and coupling

The more arguments a function signature has, the more likely this one is going to be tightly coupled with the caller function.

Let's say we have two functions, f1, and f2, and the latter takes five parameters. The more parameters f2 takes, the more difficult it would be for anyone trying to call that function to gather all that information and pass it along so that it can work properly.

Now, f1 seems to have all of this information because it can call it correctly. From this, we can derive two conclusions: first, f2 is probably a leaky abstraction, which means that since f1 knows everything that f2 requires, it can pretty much figure out what it is doing internally and will be able to do it by itself. So, all in all, f2 is not abstracting that much. Second, it looks like f2 is only useful to f1, and it is hard to imagine using this function in a different context, making it harder to reuse.

When functions have a more general interface and are able to work with higher-level abstractions, they become more reusable.

This applies to all sort of functions and object methods, including the __init__ method for classes. The presence of a method like this could generally (but not always) mean that a new higher-level abstraction should be passed instead, or that there is a missing object.

If a function needs too many parameters to work properly, consider it a code smell.

In fact, this is such a design problem that static analysis tools such as pylint (discussed in Chapter 1Introduction, Code Formatting, and Tools) will, by default, raise a warning about when they encounter such a case. When this happens, don't suppress the warning—refactor it instead.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.90.54