![]() |
|
||||||
Avoid Global VariablesWith small scripts, you’re not going to run into these types of issues often, because it’s relatively easy to keep track of everything that’s going on. Inevitably, applications become larger and more complex, and tracking down the source of a problem becomes more laborious. One of the best ways to sidestep errors is to avoid using global variables.There are two ways to minimize the use of global variables: · 1). Do not use global variables from within a function. Instead, pass in any required values as parameters to the function. Using our JavaScript example from before we can do this: · 2.) Use object-oriented programming (OOP). This mantra is similar to the first point, but on a larger scale. Instead of a collection of functions that perform related tasks, the functions become methods of an object. (A method is a function that belongs to an object.) Values can then be passed into the object in a variety of useful ways:
Here’s a quick JavaScript OOP example: Where to DeclareWhen traveling between two countries, you declare your goods at the border. Apply this analogy and declare variables at the border of the function—that is, right when you get into a function.Declaring your variables right away ensures that you haven’t accidentally embedded a variable declaration, like in a while loop, too deep in the code. It also helps ensure that you’re not reusing variable names that could erase data you’re expecting further on in the function. Scope in a Recursive FunctionA recursive function is one that calls itself, often over and over again. These are sometimes used to build tree views when data is hierarchical. When calling the same function over and over again, we’re reusing the same variable names. What happens to our variables? Take a look at this PHP example:Ignore the fact that this loop is somewhat pointless—the basic concept is that $currentvalue never becomes greater than 2. Think of each execution of a function as a self-contained entity in memory. Even when called from within itself, that new call makes a copy of itself and any variable declarations made within that function stay within it. Use ScopeUnderstanding scope will save you time troubleshooting and will make your code easier to follow. Keep your code minty fresh!
No Comments for this page. |
|
|||||||||||||||||||||||||||||||||||