Question

I noticed in a lot of scripts ( like phpbb ) that some functions are declared on the top of the script just to be used once. What the point of doing that? Are they used to make the code more readable?

For example I have a page that execute the user login, and the login is an action that can be done just there. So I declare a function for the login and I use it there.

Was it helpful?

Solution

Yes, more readable is usually the aim. And sometimes, to leave the option of re-using the code in future. Remember, a function is usually a bit of a black box: if you know how to use it, you don't really care how it works, so it can help the programmer keep track of what would otherwise be a long block of code.

Edit: your login example is a good one. It's entirely possible you'll want to login from somewhere else in your site in future, in which case, having it as a function is a very good idea. Also, having login($username,$password) is a lot clearer than a load of database lookup and setcookie() bits.

OTHER TIPS

Maybe. And you don't know whether that function is meant to be used some time in the future or even be a base for a future user-created extension. But anyway, the code makes more sense when using functions, as you have a small "main" function within whom you call other small functions rather than a huge "main" where you can't understand anything.

Much like the previous answers but having a block of code in a function leaves the door open to you or someone else more easily recognising it, isolating it and subsequently including it elsewhere.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top