19 ms·
A Guide to Naming Variables
- rectang 10y agoMost of this, even if it's not my preference, I would never bother arguing with. But I have a question about a practice that is tremendously widespread. I have real trouble with single-letter variable names like "c", for any function more than, say, 2-3 lines. I scan the code and it increases my mental load because I have to remind myself what it means. Obviously a lot of people don't have problems with this, but I do. Anybody else? Maybe it's because I jump around a lot from function to function?
- JamesBarney 10y agoI agree. I prefer this List<Host> hosts = hostService.fetchMatchingHosts(hostFilter); Set<JVMVersions> versions = JVMServiceFactory.factory(region).getApprovedVersions(), List<AvailabilityZone> zones = RegionFactory(region).getZones(); return hostUpdater.updateJVM(hosts, versions, zones); to this List<Host> hs = hostService.fetchMatchingHosts(hostFilter); Set<JVMVersions> js = JVMServiceFactory.factory(region).getApprovedVersions(), List<AvailabilityZone> zs = RegionFactory(region).getZones(); return hostUpdater.updateJVM(hs, js, zs); The top version means I can read the return line by itself and get a feel for what it does without having to skip back up a few lines. And while there definitely is a tax on longer variable names, I usually don't feel that way with single words. The brain chunks small common words, so hs probably takes just as much if not more working memory than hosts. Footnote : Just while writing this I had to look up a couple of times to remember hs, js, and zs. But I never hard to look up to to remember hosts, versions, and zones.
- BinaryIdiot 10y agoI completely agree and I was a little surprised this blog post suggested that a simple 'c' was good enough. It's not good enough. While I understand the scope between two functions is different, if the variables can be unique then I say make them unique! It makes scanning, grepping, etc all so much easier. Unless it's a very obvious index for a for loop I am against single letter variable names. Hell even if it's a for loop, if the code is so long within the loop that I have to scroll then I think the variable names need to be more obvious to keep the context with it as you scroll away from the declaration of the for loop.
- Nullabillity 10y ago> It makes scanning, grepping, etc all so much easier. Or you could use a decent editor, that keeps track of variable scopes.
- BinaryIdiot 10y ago> Or you could use a decent editor, that keeps track of variable scopes. Are you suggesting doing a find / grep inside the context of a current scope? Or just color codes / indents / marks in some way the scope? That works to a degree if an editor can do that though that still doesn't ultimately help the fact that it's a single file that you may need to search around for something. Plus not every environment will have your favorite editor setup how you like it.
- Nullabillity 10y ago> Are you suggesting doing a find / grep inside the context of a current scope? Or just color codes / indents / marks in some way the scope? That works to a degree if an editor can do that though that still doesn't ultimately help the fact that it's a single file that you may need to search around for something. At least IntelliJ will highlight all uses of the currently selected variable/method/whatever, and will quickly allow you to jump to any of them. If I'm searching for something by name then it's almost always because it's in use somewhere, and a ctrl+click will take me there instantly, without getting bogged down in false positives. > Plus not every environment will have your favorite editor setup how you like it. Sure, but how often do you actually have to work with your regular codebase in such an environment? Sure, such a rule has its uses, but in 97% of cases it's just a symptom of a poor editor setup.
- burkaman 10y agoI think it works here because you're in a context where there's just one collection. So you don't really have to remember what c means, you can see c.size() and think "this is the size of the collection", because in this context there's only one thing you could be taking the size of. If there were more than one collection, or we weren't using it in a way that makes it obvious it must be a collection, I would want a better name.
- chimprich 10y ago> you can see c.size() and think "this is the size of the collection" If you see collection.size(), you don't even need to think; the meaning is right there in your field of vision and you don't need to dedicate one part of your extremely limited short-term memory to remembering what c stands for. I can't see any advantage to shortening it to c, apart from saving a trivial amount of typing.
- teamhappy 10y agoI find that single letter variable names (or 2-letter names for that matter) really only work if both your coding style and your language allow it. You have to write short functions (5-20 LOC or something like that) in a language that encourages that style. C, Go, LISP, and Haskell (and many more) are great for this kind of thing. But object oriented languages like C++ and Java tend to have much longer functions (50-100 LOC isn't uncommon). I'm not sure the fact that they're object oriented has anything to do with that though.
- elishacook 10y agoI agree. It's not a mental tax to read a word we recognize. It's not like we have to sound it out letter by letter, we recognize its form at a glance. It's more taxing to maintain a mapping for an inherently meaningless single character. Although there are some single characters that do have meaning due to long time convention such as 'i'.
- chriswarbo 10y agoWhat about variables which are inherently "meaningless", i.e. they're only given a name in order to distinguish them from each other? For example: function flip(func) { return function(x, y) { return func(y, x); }; } function compose(func1, func2) { return function(x) { return func1(func2(x)); }; } Code like this is completely generic; we know absolutely nothing about `x`, `y`, etc. other than they're distinct arguments; we don't even know their type (they're "parametrically polymorphic"). Would it be better to call them something like `arg`, or `arg1` and `arg2`? The fact they're arguments is obvious, so that would be just as redundant as something like `int int1 = ...`. This kind of generic "plumbing" appears all the time when using a functional style, where our function's job is to take in a bunch of values and combine them in some way, without caring what they are.
- kazinator 10y agoIf the variables have no meaning other than argument placeholders in a transformation between functions, then they must not be given descriptive names that falsely hint at some deeper meaning.
- vanderZwan 10y agoYou answered your own question: such abstract (not meaningless) variables make sense when the code is completely generic. Most code however is somewhere between generic and specific, literal values, and variable names should represent that semantically. Also, I would even argue that x and y are not meaningless in this context. There's a reason you didn't write: function flip(gnarf) { return function(t, m) { return gnarf(m, t); }; } function compose(bip, boop) { return function(blep) { return bip(boop(blep)); }; } The sequences {a, b, c}, and {i, j, k}, {m, n}, {p, q}, {x, y, z} are all well-established "abstract" variable names that most of us remember from high school algebra, and all have different baggage and expectations: - a, b, and c tend to be generic labels for things, not numbers - i, j, and k are used for indices and tend to be natural numbers (or more rarely for complex numbers/quaternions, where they are floats) - m and n are used in matrices and also are used for natural numbers - in maths, p and q are often fractions - x, y, and z tend to represent coordinate systems and/or floating numbers We can combine this to create variable sequences, with subtly different meanings. For example: compare (x1, y1), (x2, y2) with (xa, ya), (xb, yb). To me, if I see foo(x1, y1, x2, y2) that implies either top left, bottom right in an axis aligned bounding box, or perhaps the first point and the second point of a line or vector, or some other situation where the two points are somehow connected in one object or shape. Using (xa,ya) and (xb, yb) however suggests I'm dealing with two distinct points.
- owenconti 10y agoI can't stand that. I like using names that don't make me think about what the variable means.
- xixi77 10y agoTBH, when reading others' code, I would generally prefer a shorter name to a similarly informative longer name, as it definitely speeds up recognition. There are a few situations when this is the case: on top of my head, (i) function arguments, (ii) implementations of mathematical formulae that already have standard conventions for notation, (iii) cases when longer variable names are not well chosen and don't tell us much (e.g. his "processElements" function is far, far easier to read than "doSomethingWithCollectionElements"), (iv) situations when there are multiple long names that only differ in the last few characters -- again, I would much rather see "in_x" and "in_y" than "ThisHereInputCoordinateX" and "ThisHereInputCoordinateY", particularly if these are a part of a formula with a few other variables involved. Might be just me and how I read things, of course -- e.g. I usually print stuff in the smallest readable font, so that I can see more of the logic at the same time, and this is definitely not the case for all people.
- nilved 10y agoHave you considered not writing functions longer than 3 lines?
- euphemize 10y agoAlso agreed. I will use single-letter variables like "c" or "x" occasionally for lambdas or anonymous functions, but that's about it. "lambda x: not x" in python - anything longer I think should be descriptive.
- cagey 10y agoI too abhor single-letter variable names. My personal convention: minimum identifier length==2. {i,j,k}->{ix,iy,iz}, c->ch.
- ambulancechaser 10y agoI'm all for descriptive names but do you really not like iterator variable names like i,j,k or x,y,z? You prepend them i (for integer i suppose)?
- bpicolo 10y agoI tend to call them index. If the loop is nested I grab functions to call inner bits. i and j especially can get crazy muddled coexisting (could you even pick two more similar letters? Capital I and l depending on the font maybe?). In general, much prefer languages where I don't ever have to index. E.g. list comprehensions are much more expressive
- ArkyBeagle 10y agoIn FORTRAN 64, variable names were significant. I was an integer, F was a float, that sort of thing. This created habits that persist to this day.
- cagey 10y agoactually i for "index" ('ix'->'index x'), not "integer"
- hnruss 10y agoAgreed. The part about 'c' seemed pretty contradictory, and without much explanation as to the exception.
- rocky1138 10y agoSingle letter variable names are valid only in two cases: -loops (for i = 0; ...) -scientific variables, in which case they should probably be constants anyway (c = speed of light in a vacuum)
- bpicolo 10y agoOne of my biggest digs with typical mathematical/scientific notation is that reading equations where there are a number of things that are variables and other things that are constants with all one letter isn't great. I WISH we had used SPEED_OF_LIGHT in math class.
- fenomas 10y agoI sometimes use one-character names as a semantic hint that the variable is short-lived and relatively unimportant. I may not know at a glance what "c" means, but I know it's something that was assigned within the last few lines, and that won't live beyond the next few.
- snarfy 10y agobool productPricingUpdatedAfterDeliveryFailedButEmailSent = false; I've seen variables with names like the above. It would have been better explained in a comment and used a short variable name. Unless you like typing it forces you to use an editor with autocomplete (which you are crazy not to use one), and IMO pollutes the code. Variables should be easy to type and read. It's a trade off.
- psylence519 10y agoIf you need that much information about a variable, I would expect, in general, that the context it lives in is doing waaaay too much and should be broken up.
- lgunsch 10y ago100% agree! I always try and remember the Single-Responsibility-Principle.
- krylon 10y agoWell, there is a middle ground between 'c' and writing a novel in a variable's name. Single letter variable names are okay for loop iteration variables, or e.g. x and y when dealing with 2D coordinates (i.e. if within the context a single letter name has useful meaning - I suspect physicists and the like find themselves in that situation often). But trying to give variables short names (which is a good thing) should not be an excuse to give them obscure names. As an extreme example, think of Perl, which has a "default variable", that has basically no name at all ($_). When used properly, one can, I guess, write marvelously succinct code, but I try to avoid it and use explicit names. The older I get, the more I tend to agree with Aristotle's general approach to ethics: Avoid extremes, seek a middle ground/moderation. I am not sure if it is a good ethical principle, but in many cases where ethics don't matter, it is a good guideline. So for Identifiers: Be short, but clear. When in doubt, choose clarity over brevity, but keep in mind that what might be clear to you could be highly obscure to somebody else. If at that point I was still in doubt, I would pick a name based on how the variable is used: The more rarely it used, and the more significant it is to the program, the more reasonable it becomes to use a verbose name, especially when it is a global variable. For locals, one can always use a short name and a comment to explain what role it plays.
- ChemicalWarfare 10y agoFor 'local utility' vars - things like loop counters, short lived array indexes/pointers, collections data (the ubiquitous k,v for 'key', 'value') - things like that, even if a block of code whose scope they are tied to is in a 15-20 line range I'm totally fine with single-letter names. Also, on the flip side, if say my chunk of code is solely dedicated to operating on a single object I'm totally fine using a one-letter name for those vars as well. Like say 'Person p' or 'WebView w' etc. These are notable exceptions though, at least as far as I'm concerned.
- Splines 10y agoPersonally I like to make even my short lived variables more verbose. If I'm iterating through a list of things, I'll call my loop var an iThing. It makes it immediately obvious if you're doing something wrong if you write NotAThingList[iThing].
- logicallee 10y agoit's obvious that computer scientists have COMPLETELY dropped the ball by not figuring out a way for anyone to write "it", "that", "which" and so on and have the IDE and language disambiguate it into what you were JUST talking about. This is stuff that my great-grandparents should have been suggesting some time after Ada Lovelace wrote about the analytical engine in 1842 or 1843. Not something I should be writing about in 2016. Yeah, okay, before always-on Internet it might make sense to have a small, unambiguous, self-contained grammar. The same is not true in 2016. Here's how you calculate the absolute value of an integer: -> "if it's non-negative, return it; if it's negative return its opposite". Here's how you calculate the absolute value of an integer if you're using any programming language written in 60 years: -> "if (argument <= 0) return argument; else return argument * -1." (or some variation) There is literally no way to refer to "it" instead of "argument" except by changing "argument" to read "a" (or "i" or "x" or "$_" or...) My point is that it's literally impossible to write "if (it > =0) return it; else return (it * -1)" if you've just mentioned "it" and you are there to check and correct the IDE if it's wrong. (Oh, wait, I should write "to correct the IDE if the IDE is wrong.") I bet 90% of human languages have a way to refer to something you've JUST mentioned without repeating a word for it. (Words like it, that, etc.) I bet 0% of computer languages let you write "it" for the last thing you just referred to, even if there is literally 1 choice in the whole function, as in my absolute value example. Ridiculous!
- ArkyBeagle 10y ago"Computer scientists" don't have an opinion much about a particular IDE; if you want that functionality in an IDE, it might be a shorter path to cause it to exist in the first place. I bet it's harder than you think. Also, IDEs are better than they used to be - I stopped using them because they caused problems in the late 20th Century. There was a proliferation of them until Eclipse got good enough to not cause problems. Eclipse still had less text editing power than some just-plain-old-editors from the 1980s. So I only use an IDE if it's the only logical choice for a development system. It usually isn't. If, as in one shop at which I worked, you constantly write, say EMACS macros and use them a lot, you will evolutionary drift away and it will make your team more and more ... linguistically isolated, which has costs in onboarding and this sort of mild narcissism about your setup. I think that dependence on an IDE is mostly a weakness, not a strength.
- drdeadringer 10y agoI agree with you. Two years from now, I'm not going to be able to remember "c" from "v" without having to think harder than I have to. If I name the variables something like what they actually mean or do, however, that's much better. I know what "particle_count" is more so than "p".
- ArkyBeagle 10y agoBeats me. So this is something that hasn't gotten any better for you over time? You should look at old school DSP code some time. :) Some of that is translating from variable names in mathematics papers. Also - for us old guys, you could take typing or you could take a math class, so many of us never really learned to type properly. So typing can be an actual consideration. Schools adapted to this later.
- detaro 10y ago> You should look at old school DSP code some time. :) Some of that is translating from variable names in mathematics papers. I feel that is sort of a valid exception. If it is common notation in the field you need to be familiar with anyways or you are implementing from a specific source, not using short names adds another layer of mental translation. If I'm implementing an algorithm from a paper I put an "implementation based on: <citation/URL>" on top and try to match it as closely as possible. (DSP code probably doesn't do the latter, because performance, but where possible)
- bobwaycott 10y agoI, as a rule, only use single-letter vars when iterating over an emumerable, in which it is clear what the single-letter var represents. Outside of that, never. The single-letter var also is usually the first letter of whatever actual items are being iterated over. Something like: for c in customers: do_something(c)
- krinchan 10y agoThe function is not very long and it's sort of pointless. Besides, what do you name it? collectionInts? That's in the declaration, right there. candidates? As obtuse (and useless) as c. If you're grepping/ag'ing for c you've got another issue, because I can't think of the context that you would grep c in a function that fits on less than 2 24-row terminal screens. At worst, /c and a few presses of 'n' is all you need once you get to the function. If you're outside the function grepping, it's because you saw printNFirstIntegers(4, someOtherVariableName). You'll hardly have named the variable (or collection literal) "c". So you'll be using ag printNFirstIntegers. To me, your request is akin to the last time I had a code review for a rake task and someone complained about the 'f' in: FileList['deploy_assets/ebextensions/*'] do |f| @helper.process_template(f, ".ebextensions/#{File.basename(f)}") end Calling it File is horribly obvious and annoying. Edit: The function name probably should be run_erb_on or something like that. None of us are free of naming sins. Lol.
- jorams 10y agoI very much agree. There are some cases where short variable names make sense. In the example the loop index is called "i", and that's good. It's good because it's just an index. The only reason it's there is because the looping construct isn't expressive enough for the desired loop semantics, so the short name means you don't have to care about it. The use of "n" is also alright. It describes a number, for which "n" is a convention. "c", on the other hand, is a horrible name. It's worse than "collection", because it's important and the scope is large enough that it's hard to skim for. "collection", however, is also bad. The variable doesn't just refer to a collection, it refers to a collection of integers. Why not call it "integers", or "numbers"? I find conventions around this to really influence the readability of the average code in different programming languages. Lots of Haskell code can get away with short variables in small functions. Their scopes are small, their purpose is incredibly generic. C code often uses short variable names despite not being concise nor generic, making it unnecessarily hard to read. Common Lisp tends to use descriptive names. It's dynamically typed and contains little type information, and yet you always know what you're working with.
- pohl 10y agoFor me it's not how many lines there are in the function, but how many lines of scope the single-character variable lives. If it lives for 2-3 lines in a 12 line function, the dude abides the name.
- andrewfromx 10y agowhen it's coding as fast as humanly possible, the last thing I want to do is slow down to think of good var names. I'll often just name something "foo" if I can't think of a good name and come back and rename it later. Sometimes it's a little better than foo but still not perfect but I'll leave that and move on to something else. I really don't like the idea that code must be perfect. Code is never perfect.
- bovermyer 10y agoBut what happens if you die and someone else has to pick up where you left off?
- Aldo_MX 10y agosomeone else is going to cry because the coder is dead and the code is unreadable
- mcguire 10y agoWell, at least someone will be happy at the wake.
- milesokeefe 10y agoThe world will stop turning and it will all have to be rewritten from scratch.
- coredog64 10y agoThe typical response of a developer inheriting legacy code from a no-longer-employed-there developer is "this is garbage, I need to rewrite it". So in that sense not only is 'foo' efficient for the original commenter, it is _also_ efficient for his/her replacement since it will present a very clear business case for a rewrite.
- MrPatan 10y agoThis is another example of how everything depends on the user. From this comment I can only assume that you code by/for yourself or with very few other people, with which you surely share a lot of time and space which makes communication in that kind of shorthand possible. And now, I want to highlight how difficult was for me to be an understanding and constructive member of society right now, and try to explain why you may be right in some cases, instead of why you're wrong in some other possibly larger number of cases, while foaming at the mouth with an eye twitching, which is what my first internet instinct was.
- kogus 10y agoGood advice. If this sort of thing is appealing to you, then read Code Complete by Steve McConnell. It's basically an entire book full of very solid advice of this sort.
- gbhn 10y agoAnother book you'll enjoy if you liked this post: "The Art of Readable Code" (http://www.amazon.com/Art-Readable-Code-Theory-Practice/dp/0596802293/ref=asap_bc?ie=UTF8 http://www.amazon.com/Art-Readable-Code-Theory-Practice/dp/0...)
- ederlf 10y agoI aggre with pretty much everything. However, some conventions only apply to strongly-typed languages (e.g: Don't Put the Type in the Name)
- RodericDay 10y agoIn dynamic languages, like Python, I think it's often good to call variables something like `fruit_list`, to quickly pick up on a bug where ie: `fruit_list == {'apple'}`.
- squeaky-clean 10y agoA convention I've always done for this is to just use a plural name. There are fewer errors based on mixing up the names than you'd think, and it's very readable. for fruit in fruits: assert fruit is not 'apple' print(fruit) assert 'banana' not in fruits etc. Especially in Python, it makes code flow very much like English. Edit: It also goes with the "don't put the type in the name" point, which I agree with in most cases. Depending on your use case, it most likely won't matter if fruits is a list, tuple, set, generator, whatever. The plural implies an iterable interface. However, if the type does matter, I will often use it in the name (in a dynamic lang like Python).
- DiabloD3 10y agoThat has always been a Java thing to me. I see it a lot in Sunacle, Apache, and Google originated code (which, for some reason, all three have their own different culture on how to write Java, but it's kind of subtle).
- squeaky-clean 10y agoMaybe! My first real coding gig was Java, so I built up a lot of habits there. I've noticed the JetBrains IDEs do this style of naming and inference automatically. I haven't written Java in a long time, but it would make sense if that's where I picked it up. I do like the convention very much though.
- 6502nerdface 10y agoI've always considered it a dangerous idiom in dynamic typed languages like Python to create identifiers that differ from each other by only a single character (fruit/fruits), point to completely different objects, and are used in close proximity to each other. It's just asking for a hard-to-detect typo that will blow up at runtime.
- akkartik 10y agoOff-topic, but blogspot links are a constant frustration for me on the phone. It's super easy for my fingers to swipe slightly left/right when scrolling and triggering blogspot's next/previous post navigation. I can even accidentally end up slightly scrolled horizontally and have no way to see the left side again. As a result I mostly ignore blogspot links. But this seems up my alley (http://akkartik.name/post/readable-bad http://akkartik.name/post/readable-bad). Anybody else run into these issues? Anybody have suggestions or workarounds? Why do technically savvy folks not notice how crappy blogspot has gotten? Edit: PSA for blogspot owners https://productforums.google.com/forum/m/#!topic/blogger/8hNsCLpEn6U https://productforums.google.com/forum/m/#!topic/blogger/8hN... http://chrisltd.com/blog/2012/03/blogger-mobile-theme http://chrisltd.com/blog/2012/03/blogger-mobile-theme
- BinaryIdiot 10y agoI hadn't realized this was a blogspot thing. I had seen this multiple times and I completely agree. Almost every single time I go to keep scrolling, somehow slightly shift my finger to the right or left and BAM I'm in another article. Very frustrating and pretty counter intuitive for how we're used to the web working.
- jakub_g 10y agoBlogspot is one of the most frustrating software out there that I interact with regularly (from HN mostly). Desktop version feels very slow and heavy, mobile version has this moronic feature of swiping to next/prev article, and countless other things that make UX really awkward. Same with Google Groups and some other Google products. It's super weird, they sit on a pile of money, hire thousands of 'best of the best' and can't get some simple things right.
- gcr 10y agoReader view on iOS makes blogspot, and lots of other articles, quite bearable. (I assume it works?)
- akkartik 10y ago
- Aleman360 10y agoI love it when people use generic names and then add a two word comment describing what it is. I also love it when people use primitives for time spans along with the units in the name or comment instead of TimeSpan/std::chrono.
- jschwartzi 10y agoMy favorite is when people use a good variable name and then put a two line comment explaining what I could gather from the variable name.
- codesnik 10y ago"rather than the elliptical vagueness of Romance languages like English" - what?
- theandrewbailey 10y agoI had a few problems with that, too. English isn't a romance language (it stole a lot of romance vocabulary, though). I guess that the author eventually gets around to explaining what he means: too much vocabulary that doesn't break down into simpler, understandable words. It reminds me of the linguistic contortions you need to do in order to write like the Thing Explainer.
- fourthark 10y agoMe three. I guess it's better said that those borrowed words don't break down easily for native speakers of English. There may be more concise ways to assemble variable names in Romance languages if you're a native speaker.
- minionslave 10y agoI had the same reaction too. After googling it to make sure, english was a germanic language like I always knew. Then I'm like, English might as well be romance because it's riddled with french words.
- weinzierl 10y agoIt's not (just) the vocabulary. Besides a the history it's primarily the inflection system that Romance languages have in common. Compare for example English with Spanish, Italian and Portuguese: en es it pt I go voy vado vou He/She goes va va vai We go vamos andiamo vamos They go van vanno vao While the Romance Languages are very similar, English is completely different.
- mixmastamyk 10y agoA good guide, but I didn't like this part: Avoid Over-used Cliches In addition to not being Teutonic, the following variable names have been so horribly abused over the years that they should never be used, ever. val, value result, res, retval tmp, temp count str Cliches? If you are trying to communicate, these names are well known ways to do that. If there is something more specific to put in there, by all means, but I often find these names useful, combined with a good function name and docs of course. Thoughts?
- kazinator 10y agoI will stop using these when smooth jazz stops punctuating turnarounds in bluesy minor grooves with a 7#9 chord.
- euphemize 10y agoAgreed with you. Perhaps if you're using temp or tmp, something could be done better, but I see no harm in using the others. If you're counting things, a variable named "count" sound perfectly reasonable to me.
- smellf 10y agoEven "temp" would be a standard name for the temporary variable used in a swap function. https://en.wikipedia.org/wiki/Swap_(computer_science)#Using_a_temporary_variable https://en.wikipedia.org/wiki/Swap_(computer_science)#Using_...
- riprowan 10y agoCame here to say this. I bumped my head hard on this part of the text - the whole point of using a cliche is that it's immediately understandable. When I come across an incrementing loop that doesn't use a cliche variable like "count" or a function that doesn't return "return" it increases my mental tax. The nice thing about using a variable like "count" or "return" throughout your function is it's immediately intuitive what's going to happen with this variable.
- guscost 10y ago
- jejones3141 10y agoGood advice about variable names (though surely "dentist" isn't all that obscure), but the example function suffers from the boilerplate that the author rightly says is a problem. Looking at the Java Collection interface, the removeIf() description sounds like it actually modifies the Collection rather than creating a new one. Is there a way in Java to do the equivalent of the following Haskell (I'm being lazy and not writing a version for Traversable) take n (filter (> 0) xs)
- lmm 10y agoYou can use the Java 8 streams interface, converting back and forth at the ends. Or there's a method in Guava-collections (won't be lazy though). Or you can use Scala.
- TheCoelacanth 10y agoIn Java it's `xs.stream().filter(x -> x > 0).limit(n)`. That's a fairly new API though, so it's not all that heavily used.
- wyldfire 10y ago> iterating through a for loop using i is a well-established idiom that everyone instantly understands. Give that count was useless anyway, i is preferable since it saves 4 characters. "Where does this idiom come from?" you might ask. Well, if I recall it's mostly due to languages like Fortran which implicitly typed identifiers starting with I through N as integers.
- ChuckMcM 10y agoexactly right. Some jokes about writing fortran in any language focus on the use of "I, J, and K" as indexes and counters. But in mathematics the common iterator in a summation is also i, j, and k so mathematicians sometimes claim ownership of the use of i as a count.
- kps 10y agoFortran, like most early programming languages, was explicitly modelled on mathematical notation. There was debate whether allowing multi-letter variable names was worth the loss of implicit multiplication. But today's programmer can write COBOL in any language.
- newobj 10y agoSince when is English considered a romance language? I thought it was majority Germanic in origin.
- dragonwriter 10y agoEnglish is a Germanic language with a strong Romance influence, thanks to the Norman Conquest. (That is to say, you are quite correct that it is not a Romance language.)
- blastrat 10y agoit's always funny to me when people talk about the Norman Conquest with respect to Romance Languages... the Normans were Vikings, Germanic. In terms of Romantic influences, it is the Normans who were conquested by Latinate language :)
- jakub_g 10y agoThis pretty cool map shows distances between languages. English is Germanic and French is Romance but they are quite close. https://elms.wordpress.com/2008/03/04/lexical-distance-among-languages-of-europe/ https://elms.wordpress.com/2008/03/04/lexical-distance-among...
- kaffeinecoma 10y agoMy guess is he's referring to the large number of romance loanwords that came into the English language as a result of the Norman Invasion.
- korethr 10y agoEnglish is a bastardized munge of a language, truthfully, with both Germanic and Romance parts. Initially it was a Germanic language, but after the Norman invasion of England, a great deal of Romance words were added to the language via the old French that the Normans spoke.
- wyldfire 10y agoNo mention of physical units? I always find it terribly frustrating when trying to read code that talks about physical dimensions like time and space without any clue as to what we're measuring. const int timeout = strtol(argv[2], NULL, 10); send_and_waitfor(&msg, timeout); When I read this code, should I take for granted that the caller and callee are using the same order of magnitude that's intended? If instead I see const int timeout_ms = strtol(argv[2], NULL, 10); send_and_waitfor(&msg, timeout_ms); then I can quickly audit whether the inputs and outputs actually preserve the convention.
- Stasis5001 10y agoIf possible, it's much better to handle physical units with the type system. If your timeout is a timedelta class (or duration/difftime/interval etc.), then this whole issue disappears.
- blastrat 10y agoNot trying to convince anybody of anything, but as a public service to expand your mind, I strongly urge anyone interested in these types of ideas to FORGET WHAT THEY THINK THEY KNOW OR HAVE HEARD and to REREAD Charles Simonyi's (he invented WYSIWYG) seminal piece of his PhD thesis which now is some 40 years old. Forget what you THINK you remember about these ideas--they've been butchered in popular understanding--read the original work and digest his system as a whole and on its own merits. [EDIT add paragraph: Simonyi's overarching idea was to implement a novel solution to a familiar problem which I'll try to state as succinctly as possible: if two programmers are independently given the same programming task, and they turn out to write down the exact same code, you have won. Maintenance and working on other people's code is now solved if it's the same code you would write yourself. That's the problem he is trying to solve while also, incredibly, speeding up the process of independently writing code.] https://msdn.microsoft.com/en-us/library/aa260976(v=vs.60).aspx https://msdn.microsoft.com/en-us/library/aa260976(v=vs.60).a... (please read past dr. dimento's introduction) Pay particular attention to his notions of "type" that lead his naming system quite logically to very opposite conclusions as OP. He's not talking about underlying implementation types, he's talking about the properties of the abtract types that you keep in your head and only attempt to capture in code. Absolutely DO encode them in the name of the variable so it is completely unambiguous what you mean, so it's a contract you will live up to; not for communicating to the compiler, for communicating to other human beings: your compiler talking to other human beings is not that effective. As a simple example, how many times have you said to your coworker "you need to pass me the file" to which they'll respond, "the file handle (by which they mean POSIX), the file name, the file path, relative, absolute, socket, URI, or do you mean the FILE pointer?" These are all notions of type that are best resolved with a shorthand unambiguous (and yes, local) language which is precise about type. It helps you track meaningful distinctions and shed meaningless. Bear in mind that this system comes from "the age of C"; as such, it helps make simple concepts that many programmers find disturbingling confusing: if "ch" means "it's a character", and p- as a prefix means "it's a pointer", then a "ch" and a "* * ppch" will have the same type. What are the attributes of that character type? You need to learn them or define them; I never said it was a C char and you shouldn't think that either; it will be only if those are the type attributes that are useful to your abstract type.
- 10y ago
- Roboprog 10y agoBit of a tangent, but here goes... It's a shame that C ... Java like languages became dominant, in that they "hide" identifier names after the type types, rather than putting the identifiers at the start of a line where they are more visible. (thank God for type inference, I guess, in newer languages) Also, I find CamelCraps an impediment to scanning the names in code, as well. This is less of an issue when the name is one word, but "we" sure seem to like our AdjectiveAdjectiveAdjectiveNoun names in Java-land :-( E.g. - qualifier qualifier AdjectiveAdjectiveAdjectiveNoun adjectiveAdjectiveAdjectiveNoun = new AdjectiveAdjectiveAdjectiveNoun(42) Or was I supposed to @AutoInject that? Please, just shoot me now.
- buckbova 10y agoMy trouble with naming standards is the diversity of naming across systems/languages. For your standard crud app you could have a database record with field ORD_NUM, service layer with property OrderNumber, and in javascript orderNumber. If all I do is live in one part of the stack this may not bother me. But when I have to add a new field and propagate it through the stack I cringe at every mapping. Is it too late to camel case everything?
- pklausler 10y agoHere's a tip along these lines: Use 'j' and 'k' for integral loop control variables, not 'i'. Both 'j' and 'k' are pretty high-value Scrabble letters and it's easier to search for their appearances in code. Apart from "break", they don't appear in the reserved words of common programming languages. (And never use 'l' as a variable name; but you knew that already.)
- deleted 10y ago[deleted]
- Camillo 10y ago> Most names should be Teutonic, following the spirit of languages like Norwegian, rather than the elliptical vagueness of Romance languages like English. Norwegian has more words like tannlege (literally "tooth doctor") and sykehus (literally "sick house"), and fewer words like dentist and hospital (which don't break down into other English words, and are thus confusing unless you already know their meaning). Not only is this vaguely racist; it's also wrong, which is worse. - English is, in fact, a Germanic language. - Using more specific words (and English has lots of words) is the opposite of vagueness. A "sick house" could be a house that contains sick people, a house that is sick itself (rotten beams?), a noble family ("house") whose fortunes have turned, etc. A "hospital" is, unambiguously, a facility where the sick are given professional care. Of course, in a different timeline "sickhouse" could have been the word for "hospital", but then it would have been a word of its own, taking up the same amount of space in your mental dictionary as "hospital" does. - Romance languages are, arguably, less vague even in their grammar. You know that thing where you just jam two words together and call it a day? You see very little of that in Romance languages. Instead, you put a preposition in there, which forces you to be more specific about the exact way in which the two things are related. - Of course, a "Teutonic" fan would then say that this is a problem with Romance language, and the ability to jam words together is what makes a language truly rich. (Because it's easier to form new words? In which case, see item 2.) And sure, it's ok to have preferences. But if you're going to be a Grammar Nazi, or a literal Nazi, you better have a clue what you're talking about.
- rmk2 10y agoWhat he means, but phases poorly, is to use compounds. On your other point, at least German is very specific with how compounds work grammatically, namely that they follow a head-right principle which defines genus and declination and which essentially relegates everything left of the head to the status of further defining the head. Additionally, none of your examples work in German for the term "Krankenhaus" (sick house/hospital) for that very reason: a sick house (a house in disrepair) would have to be a krankes Haus following general rules of declension, which would also be the grammatically correct (though completely non-idiomatic) version for a fallen noble house. And while there is a very specific way that defines how stems of a compound are related, German can mark grammatical units differently from English (and akin to Latin) by requiring the agreement of case/numerus/genus between say an adjective and a noun, specifically making it grammatically impossible for krankes Haus to be understood as hospital or Krankenhaus to be understood as a dilapidated house. edit: the above holds true for Norwegian and Danish as well, by the way.
- eevilspock 10y agoAuthor fails to follow own advice: int printFirstNPositive(int maxToPrint, Collection<Integer> c) The method name uses "N", but the param for N is named "maxToPrint". Confusing and also violates his/her wasted space rule. Instead: int printFirstNPositive(int n, Collection<Integer> c) I think the short variable names "n" and "c" are fine since they are part of the method signature and have unambiguous meaning, and also because the implementation is so short (so no problem remembering that n and c are the inputs.
- maxxxxx 10y agoAs a German I totally agree with teutonic naming. Who doesn't love words like "Umsatzsteuervoranmeldung". However, I disagree with the chapter "Remove Thoughtless One-Time Variables". I much prefer having a variable I can check in the debugger than having the result of some function passed into another function without being able to see what the value is. Any halfways good optimizer will remove the varibale anyway so there is no performance hit.
- rootlocus 10y agoIf the function doesn't have side effects (and even if it does), the IntelliJ IDEA debugger will gladly evaluate the function call and show you its result for java applications. PyCharm can also do this for python.
- maxxxxx 10y agoThe Visual Studio debugger can do that too but that works for only for functions without side effects that can be executed repeatedly. This is often not the case.
- awinter-py 10y agoI'm all for tricks that make 'coding in the small' easier, but grain of salt on this -- reading a large codebase, esp one with external dependencies, is a separate problem. In my day to day life (and not everybody is me, I know) the large program reading problem is THE problem; comprehending functions is a nice bonus but not as hard. In small functions, I wish variable names were automatic based on type. If a function has only one local of type T, it should automatically get name t or something.
- partycoder 10y agoI don't agree with this article. 1 character variables is not a good goal to have. For me, the second block is more readable than the "good" example. It has issues, but it's more readable.
- kazinator 10y agoThere is always this alternative: don't have any variables to name! (defun print-first-n-pos (n seq) [(opip (take n) (keep-if [orf zerop plusp]) (progn (mapdo (op put-string `@1 `) @1) (put-line) @1) (- n (length @1))) seq]) $ txr -i first-n-pos.tl 1> (print-first-n-pos 4 '(-1 2 3 4 5 6)) 2 3 4 1 2> (print-first-n-pos 5 '(-1 -2 3 4 -5 6)) 3 4 3 Well, @1 is technically a variable. :)