237

Code is read much more often than it is written, so you should take pity on the poor soul who will have to read the code six months from now (it may be you) and strive for the clearest, easiest to understand code. In my opinion, the first form, with local variables, is much more understandable. I see three actions on three lines, rather than three actions on ...


118

I don't share your opinion. In my opinion using global variables is a worse practice than more parameters irrespective of the qualities you described. My reasoning is that more parameters may make a method more difficult to understand, but global variables can cause many problems for the code including poor testability, concurrency bugs, and tight coupling. ...


109

Variables (or more generally: “objects” in the sense of C) do not store their type at runtime. As far as machine code is concerned, there is only untyped memory. Instead, the operations on this data interpret the data as a specific type (e.g. as a float or as a pointer). The types are only used by the compiler. For example, we might have a struct or class ...


103

Operators are just functions under funny names, with some special syntax around. In many languages, as varied as C++ and Python, you can redefine operators by overriding special methods of your class. Then standard operators (e.g. +) work according to the logic you supply (e.g. concatenating strings or adding matrices or whatever). Since such operator-...


98

Some highly upvoted comments stated this, but none of the answers I saw did, so I will add it as an answer. Your main factor in deciding this issue is: Debuggability Often, developers spend far more time and effort debugging than writing code. With local variables, you can: Breakpoint on the line where it's assigned (with all the other breakpoint ...


92

That naming convention is often used when people want to be able to give a variable the same name as its type. For example: Employee employee; Some languages even enforce that capitalization. This prevents having to use annoying variable names like MyEmployee, CurrentEmployee, EmployeeVar, etc. You can always tell if something is a type or a variable, ...


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 ...


69

A variable is a logical construct that goes to the intent of an algorithm, whereas a memory location is a physical construct that describes the operation of a computer.  Generally speaking, in order to execute a program there is (compiler generated) mapping between the logical notion of a variable and the storage of the computer. (Even in assembly language ...


68

You should avoid global variables like the plague. I wouldn't put a hard limit to number of arguments (like 3 or 4), but you do want to keep them to a minimum, if possible. Use structs (or objects in C++) to group together variables into a single entity and pass that (by reference) to functions. Usually a function gets a structure or object (with a few ...


57

We're talking about cognitive load, not syntax. So the question is... What is a parameter in this context? A parameter is a value which affects the behaviour of the function. The more parameters, the more possible combinations of values you get, the harder reasoning about the function gets. In that sense, global variables that the function uses are ...


54

The other answer explains well the technical aspect, but I'd like to add some general "how to think about machine code". The machine code after the compilation is pretty dumb, and it really just assumes that everything works as intended. Say you have a simple function like bool isEven(int i) { return i % 2 == 0; } It takes an int, and spits out a bool. ...


50

I like this question. The following is from my head but I think it fits quite well. status is used to describe an outcome of an operation (e.g. success/fail). state is used to describe a stage in a process (e.g. pending/dispatched). I also like this definition: status is a final (resulting) state. It is quite clear when applied to programming. Much less ...


48

Only if it makes the code easier to understand. In your examples, I think it makes it harder to read. Eliminating the variables in the compiled code is a trivial operation for any respectable compiler. You can inspect the output yourself to verify.


47

You are comparing variable declarations to #defines, which is incorrect. With a #define, you create a mapping between an identifier and a snippet of source code. The C preprocessor will then literally substitute any occurrences of that identifier with the provided snippet. Writing #define FOO 40 + 2 int foos = FOO + FOO * FOO; ends up being the same thing ...


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 ...


39

A design constraint of the C language was that it was supposed to be compiled by a single-pass compiler, which makes it suitable for very memory-constrained systems. Therefore, the compiler knows at any point only about stuff that was mentioned before. The compiler can't skip forward in the source to find a function declaration and then go back to compile a ...


37

Having many parameters is considered undesirable, but turning them into fields or global variables is a lot worse because it doesn't solve the actual problem but introduce new problems. Having many parameters is not in itself the problem, but it is an symptom that you might have a problem. Consider this method: Graphics.PaintRectangle(left, top, length, ...


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

There isn't any. It is what most people do, so it has become the standard because that is what everyone does. A lot of literature follows this convention so people picked up the habit. The convention isn't as important as the consistency across the code. As long as everything is named in a consistent manner so that I can tell what things are from looking ...


35

Properly naming things is hard. Very hard. If you look at it the other way, you can also take this to mean that properly named things are important. (Otherwise, why would you have spent the effort naming it?) But, sometimes, the names of things just aren't important. That's why we have stuff like anonymous functions ("lambdas"), for example: because ...


35

IMHO your question is based on a misunderstanding. In "Clean Code", Bob Martin does not suggest to replace repeated function parameters by globals, that would be a really awful advice. He suggest to replace them by by private member variables of the class of the function. And he also proposes small, cohesive classes (typically smaller than the 600 lines of ...


30

Because C is a single-pass, statically-typed, weakly-typed, compiled language. Single-pass means the compiler does not look ahead to see the definition of a function or variable. Since the compiler does not look ahead, the declaration of a function must come before the use of the function, otherwise the compiler does not know what its type signature is. ...


29

Your question "is it a good practice to eliminate a local variable if it is just used one time in the scope?" is testing the wrong criteria. A local variable's utility does not depend on the number of times it is used but whether it makes the code clearer. Labelling intermediate values with meaningful names can improve clarity in situations such as the one ...


28

SimpleNamespace is basically just a nice facade on top of a dictionary. It allows you to use properties instead of index keys. This is nice as it is super flexible and easy to manipulate. The downside of that flexibility is that it doesn't provide any structure. There is nothing to stop someone from calling SimpleNamespace(x=ax, y=ay) (and del a.z at some ...


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 ...


26

1. Why the standard exists? After all, wouldn't it be better to let everyone write the code according to personal preference, and stop talking about which standard is better? The fact is that when you're habituated to one style, it is more difficult to read code which uses a different style. Your brain spends more time trying to understand the convention (...


26

I don't think there's something like an 'official' convention. As far as I know, the following is considered good practice by many experienced C# developers: PascalCase for public member variables (string MyName = "James") camelCase for local variables (string myName = "James") _leadingUnderscore for private member variables (string _myName = "James") ...


26

A person named Jack Dahlgren claims on Quora he invented the term in 2002 when he worked at Intel. Here's what he posted at above link: I believe that I am the one who coined this term back in 2002 when I was at Intel and we were evaluating Sharepoint Team Services. Based on the unfortunate tendency of Sharepoint to escape spaces in names with [...


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.


21

If your loop does nothing but use a variable for counting for(int i = 0; i < 10; i++) { System.out.println("Stop it! I really mean it!!"); } then yes, this is the best name you could use. Anything longer cannot possibly make the semantics any more obvious, but takes much longer to read. If the variable is used inside the loop, a meaningful ...


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