276

Protected variables should be avoided because: They tend to lead to YAGNI issues. Unless you have a descendant class that actually does stuff with the protected member, make it private. They tend to lead to LSP issues. Protected variables generally have some intrinsic invariance associated with them (or else they'd be public). Inheritors then need to ...


236

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


191

The term 'payload' is used to distinguish between the 'interesting' information in a chunk of data or similar, and the overhead to support it. It is borrowed from transportation, where it refers to the part of the load that 'pays': for example, a tanker truck may carry 20 tons of oil, but the fully loaded vehicle weighs much more than that - there's the ...


130

Your problem appears only when your methods are long and are doing multiple tasks in a sequence. This makes the code harder to understand (and thus maintain) per se. Reusing variables adds on top of this an extra element of risk, making the code even harder to follow and more error prone. IMO best practice is to use short enough methods which do one thing ...


112

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


110

Consistency is king; pick one or the other, but do it consistently everywhere. That said, I prefer the first variation, because it doesn't violate camelCase (doing so means you have two style rules to remember, not just one). Two capital letters is sometimes used because of this, but an ID is really just a form of Id-entification.


107

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


104

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


93

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


88

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


76

TL;DR: In the context of .NET class libraries, Microsoft recommends that you use Id. This is slightly counter-intuitive, since it's a rare example of an abbreviation that is allowed / recommended (abbreviations are generally frowned upon). If we're talking about C# or .NET class library conventions, Microsoft has some fairly well defined naming guidelines ...


74

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


70

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


66

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


60

All names should be meaningful. If _ was a well known standard at your company or in the wider community, then it would be meaningful as a "name that does not matter". If it's not, I would say it's bad practice. Use a descriptive name for what you refer to, especially since the name might matter in the future.


56

The most important rule to follow in these cases is consistency: Do as everyone else does. For instance, look at your language's XML APIs to see how they do it. Java names classes like SAXParser and DOMException, .NET names classes like XmlDocument. Based on that, I'd say "ID" in Java, "Id" in C#. However, I've seen that Java EE 6 has an annotation named ...


55

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

It's really the same reason you avoid globals, just on a smaller scale. It's because it's hard to find everywhere a variable is being read, or worse, written to, and hard to make the usage consistent. If the usage is limited, like being written in one obvious place in the derived class and read in one obvious place in the base class, then protected ...


52

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


51

In C/C++, a number followed by a letter is considered to be a numeric constant and the string that follows, qualifies the type of the constant. So for example (these are VC++, not sure how standard they are): 0 - signed integer 0l - signed long integer 0u - unsigned integer 0i64 - 64 bit signed integer So a) it is easier for the lexer as Daniel said but ...


49

Variable reuse in a method is a strong sign that you should refactor/split it. So my answer would be that you shouldn't reuse them, because if you do then it would be that much harder to refactor it later.


49

The convenience of the people implementing the lexer. (No, seriously, that is about it. Various languages have other reasons, but it ultimately comes down to that.)


48

If this is a method variable, it really depends on readability. Seeing as you already have the type name in both the variable declaration and the method return type, you might as well use result - it is descriptive of the role of the variable.


47

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.


46

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


44

I would say that it's an acceptable practice. This is a rare instance where I would consider the majority to be wrong and in need of updating their knowledge of recent programming ideas. In many languages, particularly ML-based functional languages like Haskell and OCaml, it is extremely common to use _ as an "unused" variable. Even Lua, which doesn't ...


43

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


40

Cross-reading is made easier if the variable is named result. This makes your intention clear.


38

In similar situations I try to find synonyms. In this case I would use "recharge" for the verb. The "re-" is slightly redundant, but the meaning is clear. Using the simple "charge" for the remaining charge in the battery is ambiguous because it doesn't specify any physical units. I would prefer "availableAmpHours", "hoursUntilRecharge" or something ...


37

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


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