Hot answers tagged

244

This type of function / operation is called Idempotent Idempotence (UK: /ˌɪdɛmˈpoʊtəns/,[1] US: /ˌaɪdəm-/)[2] is the property of certain operations in mathematics and computer science whereby they can be applied multiple times without changing the result beyond the initial application. In mathematics, this means that if f is idempotent, f(f(x)) = f(x), ...


234

It appears that these variable names are based on the abbreviations you'd expect to find in a physics textbook working various optics problems. This is one of the situations where short variable names are often preferable to longer variable names. If you have physicists (or people that are accustomed to working the equations out by hand) that are ...


205

I had the same question about a year ago so I looked at some code myself. Here is what I found (constants were ALL_CAPS in every project, by the way): ╔═══════════════════════╦═════════════╦════════════╦══════════════╦════════════╦════════════╗ ║ PHP Project ║ Classes ║ Methods ║ Properties ║ Functions ║ Variables ║ ╠════════════════════...


189

Whilst many, including "Uncle Bob", advise not to use I as a prefix for interfaces, doing so is a well-established tradition with C#. In general terms, it should be avoided. But if you are writing C#, you really should follow that language's conventions and use it. Not doing so will cause huge confusion with anyone else familiar with C# who tries to read ...


119

A toXYZ() function is expected to do a conversion, and to return a new independent object (though immutability allows for optimization, java.lang.String.toString() just returns the object). As an example, in C++ we have std::bitset::to_ulong() which can easily fail, and a whole plethora of to_string(), all doing a (more or less) complex conversion and ...


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

The reason the software uses those names is because the datasheets use those names. Since code at that level is very difficult to understand without the datasheet anyway, making variable names you can't search is extremely unhelpful. That brings up the question of why datasheets use short names. That's probably because you often need to present the names ...


105

Is vs. Can According to the Microsoft naming convention recommendations, both "Is" and "Can" are OK (and so is "Has") as a prefix for a Boolean. In plain English, "Is" would be used to identify something about the type itself, not what it can do. For example, IsFixed, IsDerivedFrom, IsNullable can all be found in CLR types and methods. In all of these ...


89

Variables with short lifetimes should be named shortly. As an example, you don't write for(int arrayCounter = 0; arrayCounter < 10; arrayCounter++) { .... Instead, you use for(int i .... In general rule of thumb it could be said that the shorter the variable scope the shorter the name should be. Loop counters are often only single letters, say i, j and k....


85

I use Get when I know the retrieval time will be very short (as in a lookup from a hash table or btree). Find implies a search process or computational algorithm that requires a "longer" period of time to execute (for some arbitrary value of longer).


80

I don't think anyone can explain it better than Martin Fowler does, further down the article you linked to. For this new breed of containers the inversion is about how they lookup a plugin implementation. In my naive example the lister looked up the finder implementation by directly instantiating it. This stops the finder from being a plugin. The approach ...


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


68

Let's say you have some sort of "repository" class, and that repository is responsible for handing data to you from a data source. The repository could establish a connection to the data source by itself. But what if it allowed you to pass in a connection to the data source through the repository's constructor? By allowing the caller to provide the ...


68

In .NET, you often have pairs of methods where one of them might throw an exception (DoStuff), and the other returns a Boolean status and, on successful execution, the actual result via an out parameter (TryDoStuff). (Microsoft calls this the "Try-Parse Pattern", since perhaps the most prominent example for it are the TryParse methods of various primitive ...


68

Sure there is a good reason to name it more explicitly. It's not primarily be the method definition that should be self-explanatory, but the method use. And while findById(string id) and find(string id) are both self-explanatory, there is a huge difference between findById("BOB") and find("BOB"). In the former case you know that the random literal is, in ...


63

I would say that find may fail but get shouldn't.


63

For an enum option you should use title case like Default. Since C# is case-sensitive it will not collide with the reserved keyword. See .net Naming Guidelines. Since all public members should be title case in .net, and all reserved names are lower case, you shouldn't really encounter this except with local variables (including parameters). And locals would ...


61

Zipf's Law You yourself can observe by looking at this very text that word length and frequency of usage are, in general, inversely related. Words that are used very frequently, like it, a, but, you, and and are very short, while words that are used less often like observe, comprehension, and verbosity are longer. This observed relationship between ...


61

Should boolean methods always take the affirmative form, even when they will only ever be used in the negative form? Making rules about such things seems a little much -- I wouldn't want to see a guideline in a coding standards document that says thou shalt not use negative names for boolean properties. But as a matter of personal style, I think trying to ...


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.


59

English is a lingua franca/lowest common denominator for a reason. Even if the reason is conceptually as weak as "Everybody does it", that's still a rather important reason. Going against common practice means that you have to understand Dutch to make sense of the data structures in yor software. There's nothing wrong with Dutch, but the probability that ...


58

I would not name the method as your co-worker suggested. The method name should indicate what the method does. A name like PerformSqlClient216147Workaround does not indicate what it does. If anything, use comments that describe the method to mention that it is a workaround. This could look like the following: /** * Cast given right-hand SQL expression. * ...


57

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


56

Not really, as booleans are not always used to indicate that an object "is" something. "has" is an equally valid prefix "was", "can" are also valid in particular circumstances, also, I have seen the suffix "Able" used. So Object herring:- isFish = true isCat = false hasScales = true hasFur = false canSwim = true wasEgg = true eatAble = true Object ...


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


51

There is no definitive naming convention in PHP, and they differ by framework: Zend does not permit underscores Symfony also encourages camelCase Wordpress encourages underscores and does not like camelCase CodeIgniter also promotes underscores So: Use whatever your framework uses or create your own naming convention. At least for function names and ...


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


49

Golden Hammer The golden hammer is a tool chosen only because it is fancy. It is neither cost-effective nor efficient at performing the intended task. source: xkcd 801 (Despite the down-votes, I stand by this answer. It might not exactly be the opposite of re-inventing the wheel semantically, but It fits every example mentioned in the question)


49

The precise term for this (as Woofas mentions) is idempotence. I wanted to add that while you could call your func1 method idempotent, you could not call it a pure function. The properties of a pure function are two: it must be idempotent and it must not have side effects, which is to say, no mutation of local static variables, non-local variables, ...


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.


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