Re: Function size

From: Date: Tue, 29 May 2012 20:56:46 +0000
Subject: Re: Function size
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-318023@lists.php.net to get a copy of this message
> The art of software development is in taking a problem, breaking it up in to bite-size chunks, > and putting those chunks together to form a practical solution. Anyone who considers themselves a > "better" programmer because their functions are large due to their ability to handle large > functions needs to keep their ego in check. Mental capacity has nothing to do with it. > > My philosophy for functions is simple... a function does one well-defined, discrete task, and > it does it well. The inputs are clearly specified, and the potential outputs/exceptions are fully > understood. Sound familiar? These requirements make it incredibly easy to write unit tests for the > code. > > The number of times a function is used does not enter my field of interest. It's > irrelevant, as is the number of lines in each function. Following this philosophy does naturally > lead to fairly small functions, but as you move up the levels of abstraction they tend to grow > larger. For PHP, I consider code in a file that's not within a function to be a function in > itself, and the same philosophy applies. > Stuart, Your philosophy is interesting. Of course, a function should have one well-defined and discrete task, but it is not always clear what one task is. Let me take an example of a list. For example, you want to write a function that removes an element from a list. In this example, we will only use this list to remove items from it, so the code required here won't be used another time. Now you have a few possibilities: 1) (This one is probably Tony's approach): Write a single function that searches the element and removes it from the list. 2) (My approach): Write a search function first, even though we're not going to use it elsewhere), then write a delete function that uses the search function to find it and remove it. 3) (Crazy approach ;)): Write a function that gets the next element in the list, write a search function that uses the previous one. Write a delete function that uses the search function, and then calls a function that removes the actual element. With your philosophy all three can fit. The other interesting part in this discussion is the limited mental work area. I assume that this is true, supported by the related studies, makes me feel that we should write code as compact as possible, right? - Matijn

« previous php.general (#318023) next »