Hot answers tagged

110

No. There are several reasons why: Variables with meaningful names can make code easier to comprehend. Breaking up complex formulas into smaller steps can make the code easier to read. Caching. Holding references to objects so that they can be used more than once. And so on.


73

It is indeed a good practice to keep your variable's scope small. However, introducing anonymous blocks into large methods only solves half the problem: the scope of the variables shrinks, but the method (slightly) grows! The solution is obvious: what you wanted to do in an anonymous block, you should be doing in a method. The method gets its own block and ...


42

Rule of thumb: variables should always be in - or as close as possible to - the scope where they are needed. Another way to phrase it is that variables should be enclosed inside the context in which they make sense and are actually useful. Most often you will want to declare your incrementing variable along with the for statement. Sometimes you will declare ...


41

Because the more things you have to deal with in any task the harder it becomes. For example, try patting your head. Then try patting your head and counting backwards from 1000. Then try patting your head counting backwards from 1000 and hopping on one leg. Then try patting your head counting backwards from 1000 and hopping on one leg and singing the ...


36

First, speaking to the underlying mechanics: In C++ scope == lifetime b/c destructors are invoked on the exit from the scope. Further, an important distinction in C/C++ we can declare local objects. In the runtime for C/C++ the compiler will generally allocate a stack frame for the method that is as large as may be needed, in advance, rather than ...


35

If your function is so long that you cannot recognize any unwanted side effects or illegal reuse of variables any more, then it is time to split it up in smaller functions - which makes an internal scope pointless. To back this up by some personal experience: some years ago I inherited a C++ legacy project with ~150K lines of code, and it contained a few ...


35

I'm generally in favor of nested functions, especially in JavaScript. In JavaScript, the only way to limit a function's visibility is by nesting it inside another function. The helper function is a private implementation detail. Putting it at the same scope is akin to making a class' private functions public. If it turns out to be of more general use, it's ...


27

In my opinion it would be more clear to pull the block out into its own method. If you left this block in, I would hope to see a comment clarifying why you're putting the block there in the first place. At that point it just feels cleaner to have the method call to initializeKeyManager() which keeps the password variable limited to the scope of the method ...


25

Engineering is, abstractly, managing complexity. Software Engineering is, abstractly, managing complexity in software! Scope is a tool to help manage complexity, like any tool it can be used or abused, and sometimes can be overkill. Without scope, you would have to track the entire state of the program at all times when writing or modifying it. Without ...


22

Often if you find places to create such a scope it's an opportunity to extract out a function. In a language with pass-by-reference you would instead call swap(x,y). For writing the file that would be advisable to use the block to ensure RAII will close the file and free up the resources as soon as possible.


17

They can be useful in Rust, with it's strict borrowing rules. And generally, in functional languages, where that block returns a value. But in languages like Java? While the idea seems elegant, in practice it's rarely used so the confusion from seeing it will dwarf the potential clarity of limiting the variables' scope. There is one case though where I find ...


16

Agree, variables which are not necessary and does not improve the readability of the code should be avoided. The more variables which are in scope at a given point in code, the more complex that code is to understand. I don't really see the benefit of the variables a and b in your example, so I would write the version without variables. On the other hand ...


15

You should put it at global scope, for several reasons. Nesting a helper function into the caller increases the length of the caller. Function length is almost always a negative indicator; short functions are easier to understand, to memorize, to debug and to maintain. If the helper function has a sensible name, reading that name is enough without needing ...


13

I assume you do not know, yet, of Expression-Oriented languages? In Expression-Oriented languages, (nearly) everything is an expression. This means, for example, that a block can be an expression as in Rust: // A typical function displaying x^3 + x^2 + x fn typical_print_x3_x2_x(x: i32) { let y = x * x * x + x * x + x; println!("{}", y); } you may ...


11

Well, currently the main difference is a namespace is designed to be augmented in separate files. If you try to add a new nested class to a class, you get: test1.cpp:3:7: error: redefinition of ‘class NamespaceClass’ However, it only works that way because it was defined that way. It wouldn't be that difficult to rework the compiler to append to a class ...


11

The normal way is to move the "so something with x" line(s) also within the try block: std::map<char, int> mymap {...}; try { int& x = mymap.at('a'); // do something with x } catch (out_of_range& e) { return; } The nice thing about exceptions is that when an exception is thrown, all code between the throw and catch locations is ...


11

Minimizing your use of global variables means that you don't have to think about how these variables are interacting with your functions. How many different places in your code are writing to that global variable? Your global variable is the center of a spider web; every place it touches is adding unnecessary complexity and coupling. Eliminate the ...


11

In addition to the other answers, I'd like to point something else out. The benefit to keeping a variable's scope small isn't just reducing how much code syntactically has access to the variable, but also reducing the number of possible control-flow paths that can potentially modify a variable (either by assigning it a new value or calling a mutating method ...


10

If you are asking for several parameters at the beginning, and these parameters never change, and need to be passed together, use a struct: struct options { bool isDebug; int numberOfDigits; char userName[40]; }; Then you don't have six arguments, where only two are variable, but rather just three: doItNow(int speed, float precision, struct ...


10

Not sure what you mean with reference driven programming. From what I gather, you're wondering what the advantages of event-driven programming are as opposed to writing code, and then using a bunch of branches to determine when to call a given method. Before I set off, allow me to be pedantic and point out that: a module can't listen for any event, nor can ...


8

I'm going to propose a third path, to place both functions within a closure. It would look like: var functionA = (function(){ function functionB() { // do stuff... } function functionA() { // do stuff... functionB(); // do stuff... } return functionA; })(); We create the closure by wrapping the ...


8

Each computer language has its strengths and pitfalls. Each has its own coding standards/practices often accepted, built and dictated by the community around it. Because programming is a precise art I would say, unless there is a good reason to do something, you shouldn't. Now there are very good reasons to declare variables close to where they are used: ...


8

In theory, function scope should actually be faster - variables are typically created in a stack frame, and function scope would only create that stack frame once, while block scope would need to repeadedly open up a new stack frame in every block. In practice, there are several facts that invalidate that initial assumption: No compiler is forced to create ...


7

Dynamic scoping and dynamic typing have two things in common: they have something to do with variables, and they both contain the word “dynamic”. What does “dynamic” mean here? Something is dynamic if changes with time. With dynamic typing, the type of a variable may change with time. That means it is no longer meaningful to talk about the type of a ...


7

No, this is lexically scoped to a function, just like a function parameter. It basically works like an implicit parameter. Dynamic scoping means that if a variable is defined in a function, it is also visible inside functions called from this function (and functions called from those functions and so on). This is not what happens with this though. Each ...


6

Not 100% sure I know what you're asking. But, I get the sense you're at a point where event-driven programming doesn't feel "real" enough -- or like you're at the mercy of someone else's event system. Or like your application isn't really "doing" anything. Or like it's just a bunch of disparate methods that you're feeding another application. So. Suppose a ...


6

The issue with the way you describe it (I don't know coffeescript myself) is that it makes it too easy to break existing code without realizing it. Let's say you have this code: bar = 5 // 100 lines of code f = () -> foo = 12 null // 100 lines of code print bar Now you decide that "bar" is a lousy name and you rename the global to "foo". ...


6

General case: Is there a case where using blocks only to reduce variable scope makes sense? It is generally considered good practice to keep methods short. Reducing the scope of some variables can be a sign that your method is quite long, sufficiently so that you think the scope of the variables needs to be reduced. It this case, it's probably worth ...


Only top voted, non community-wiki answers of a minimum length are eligible