At what point should you change your script to a function

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
impulse()
Forum Regular
Posts: 748
Joined: Wed Aug 09, 2006 8:36 am
Location: Staffordshire, UK
Contact:

At what point should you change your script to a function

Post by impulse() »

I'm still not in the habit of creating functions or classes in whatever I write. Really I am just asking for some advice about how often I should be writing functions. I don't fully understand OOP yet so we'll leave this out.

Do you create a function at every change possible or do you tend to use them as soon as you see yourself writing the same bit of code twice?

Do you see it worth the hassle of having to work out a function that can handle 2 types of situation but run similar code or do you find it best to whack an if statement around 2 similar pieces of code?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

If the code is sufficiently complex or is needed multiple times, it's often time to make it a function.
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post by Ambush Commander »

In Fowler's words: First time, just do it. Second time, do it, but take note. Third time, refactor.

If the code duplicated is sufficiently long, I'd turn it into a function on the second time.
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

As you begin to develop more applications you start to realize that some code will be used more than once. Time for a function. As those functions begin to appear in more and more code but in different context's it might be time for a class.

For testing code, I will almost throw down some procedural stuff. But that is quite literally to test PHP functions. Once I use them, they will almost always go into a function/method.
User avatar
The Phoenix
Forum Contributor
Posts: 294
Joined: Fri Oct 06, 2006 8:12 pm

Post by The Phoenix »

At the latest, when you have a consistent and defined set of behaviors, inputs, and outputs. If you get that far, you should make it into a function.
Post Reply