Today I’m going to be focusing on function length and scope. I came to writing this post after scouting around Google for a little while and finding a number of people asking the question: ‘how long should my functions be?’, or ‘are my functions too long?’. While the answer to this is always going to be subjective, I’ll try my best to answer it and provide rationale where appropriate.
Functions should focus on one task
If your functions have a broad scope, and are focusing on more than one task, then it is likely that they are too long. By keeping functions focused on a single task it’s possible to keep function length to a minimum.
This coding style of breaking your code up into small logical blocks brings with it many benefits, some of which are discussed below.
Short functions can be self documenting
In the past, I often wrote long functions that would get so unruly that I’d write inline documentation alongside the code. This type of documentation can be often be made redundant by breaking the code down into smaller functions with descriptive names.
The function below, whilst not exactly lengthy, demonstrates this.
function showMessages() { /// check if user is logged and has admin privileges if ($_SESSION["logged"] == 1 && $_SESSION["privileges"] == 1) { / echo "Hi Admin"; } echo "Do something else here..."; }
While the comment maybe helpful, it’s possible to achieve the same level of clarity by separating the ‘is admin’ check into another function. This also brings other benefits which will be discussed later.
function isAdmin() { if ($_SESSION["logged"] == 1 && $_SESSION["privileges"] == 1) { return true; } return false; } function showMessages() { if (isAdmin()) { echo "Hi Admin"; } echo "Do something else here..."; }
Whilst this is probably not the best example (since the function is quite small and easy to follow to begin with), hopefully it communicates the message. You can instantly look at the second example, and without the need for further comprehension, understand that the message is being shown to admin users only.
Short functions are easier to comprehend & follow
When writing code it’s always a good idea to make it as comprehensible as possible. Why? Well, when writing the code you can probably understand it at a glance. However, when you come back to it later, without it fresh in your memory, you may find yourself wasting precious time having to step through the function line-by-line just to grasp the intention.
To make your code more comprehensible, break it down into small specific blocks. The next guy to read over it will thank you; remember the next guy may very well be you!
Just think about it, imagine looking at an unfamiliar codebase & seeing a mammoth function which spans 1000 lines. I know, it’s an extreme example, but at some point while looking over that function you are going to lose your trail of thought and have to backtrack to get an understanding.
…you’re bound to run into an upper limit of understandability as you pass 200 lines of code - Steve McConnell, Code Complete.
Short functions are easier to test.
Generally speaking the larger the function, the larger the number of possible outcomes. When you’re looking at a function with 200 lines for example, it’s likely to have a bunch of conditional statements, each one changing the potential outcome or result of the function. When writing the test you’ll need to account for each of these outcomes, making it a gruelling task for even the most experienced coder. In some cases it’s probably not going to be possible to test a function of this size.
Short functions allow for easy re-use (DRY)
If you’ve not heard the acronym DRY before, you’ve probably been living under a rock somewhere. Welcome back to reality!
‘DRY’ stands for ‘do not repeat yourself’, it’s a software principle aimed at reducing repetition. It’s a very simple but powerful principle, and it’s actually very easy to adhere to. Are you repeating code somewhere in your application? Then it’s very probably you’re doing something wrong and you should reconsider your code.
Applying the principle to your functions will help keep them short, concise and re-usable. As an example, consider the ‘isAdmin’ function mentioned earlier. Initially the logic used to check if a user had admin privileges, was held within the ‘showMessages’ function. If the logic was needed elsewhere, for example, to determine whether or not a user was allowed access to a certain page, it would have to be duplicated. However, after being refactored, it would be possible to simply call the ‘isAdmin()’ function.
Tips & Advice
I’d like to explicitly note that I’m not saying you should arbitrarily break up your functions just to make them shorter. You should however break them up where it makes sense. For example, if you have a huge function, let’s call it ‘hugeFunction()’, don’t just randomly pick a section and then break it down into steps such as ”hugeFunctionPartOne()’ and ”hugeFunctionPartTwo()’. Take the time to look at your functions and break it up where it makes sense.
For example, imagine a function that logs users into a website. A hugely simplified example might authenticate user details and then set some session variable to indicate they are logged in. In this example, you can easily identify two separate tasks, authentication and handling sessions. It would be sensible to separate these tasks into separate functions.
To conclude then, it would seem that writing short specific functions makes code easier to comprehend, easier to test, reduces repetition, and as such makes the code easier to maintain. It’s important to understand why & how smaller functions can provide these benefits, so that you have the ability to identify where/when a separate function might make sense. Breaking a function up arbitrarily, or imposing certain conditions upon your functions – such as having an arbitrary maximum length (30,40 lines etc) – is not useful and will only cause you problems.
The post PHP – function length appeared first on Weebtutorials.