41 ms·
Is anybody else using ridiculously long variable names?
I've seen our own codebase end up employing rather long names pretty much everywhere, things like:
val documentAndPdfSavedOnDiskJsonStates = ...
val resumeAndPortfolioThumbnailsJsonStates = ...
Is this worth debating? Good idea/non-issue/binary size issues maybe?
Best regards!
- electic 10y agoI do as a way to self-document the code. Many people who I have worked with love this because the code is easier to read, easier to understand, and becomes more maintainable. Just my two cents.
- bmer 10y agoI did some programming for a civil engineering firm, where long, descriptive variable names were also important for making code easier to read and understand. In this case, it was necessary because the code would have to be reviewed by others to pass QC. Just my two cents, added to yours, to make four.
- underscoremark 10y ago$0.06 Its not just for other developers (when I revisit something I've written months/years ago). But yeah, when I have to review code with Testing/QA, who aren't full time developers, it makes it much easier to step them through what is being done. -- ps: especially since I'm always sparse on comments...
- asher_ 10y agoThis. The general rule I have my teams follow is that I should be able to jump into the middle of a bit of code and understand what all the variables are and the methods do etc from their names. If you do this, then you'll find the amount of inline comments you need is drastically reduced, because you're basically saying the same thing in the comments that the variable and method names tell you.
- bluejekyll 10y agoYep. I used to not do this, but now, self documentation and clear understanding of how that variable should be used is awesome. In Rust I've even started doing something additional which is use the shadowing feature. This was always a big no-no in other languages, some don't allow it, others do something different, but in Rust it can be used safely to reduce the explosion of variables in certain contexts. This helps reduce the need for distinctions between variables, allowing for shorter names.
- MichaelGG 10y agoRebinding variables (let age = "123"; let age = int(age)) is excellent and it's a shame more languages don't let you use it. It lets you keep immutability while making sure an old value isn't used.
- maxxxxx 10y agoMake sense to me. Just avoid names like "longinteger1". This doesn't mean anything.
- GFK_of_xmaspast 10y agoWhat kind of horribly constrained environment are you running on that you're worried about long variable names making your binaries too big.
- amorroxic 10y agoMea culpa, wasn't meant to be dumb though your observation is spot on. Consider it just literature, euphemistic - not ideal indeed - effort.
- MichaelGG 10y agoObfuscators for Java and .NET often strip out a fair amount of binary size by renaming most things to a single char.
- flukus 10y agoHow big are you're .net dlls/exes? Most I see are less than 100KB, with the ones bigger than that containing a lor of resources (sql, icons, etc).
- gravypod 10y agoGroup variables that all track the same thing into an object. So you csn have saved_state.tracked_picture. Makes it clear what group something is in and what the name of that data is meant to be. Much easier to parse.
- runesoerensen 10y agoI can highly recommend reading the "Meaningful Names" chapter in Clean Code for practical and useful advice on this topic (some good notes here http://www.itiseezee.com/?p=83 http://www.itiseezee.com/?p=83)
- bahmboo 10y agoYes, more so when they are used infrequently e.g. maxAllowedInvalidAuthenticationAttempts. Autocomplete is your friend. I try to make it very explicit and not just a long word bag. I use short generic names when context is obvious: index, count, max, min.
- deleted 10y ago[deleted]
- joshka 10y agoBeing somewhat pedantic here, but do you need 'max' in that? Also, perhaps even 'Invalid' is unnecessary as regardless of the last attempt being invalid or valid you're going to let the user attempt it. e.g. say this number is 3, you're going to stop authenticating at either 3 fails, or at 2 fails then a success (because the person is authenticated). ;)
- MichaelGG 10y agoOnly for globals or where you really, really need it. For locals and lambdas, I try to use 1 or 2 char vars. Usually the first letter of whatever the type is. XmlNode -> xn. Event -> e. Longer if needed, but hopefully that's rare. Really long names in functions just make reading harder. I am not sure it makes things actually clearer. Can someone understand the code without actually understanding the function? Can they make an edit?
- runesoerensen 10y agoHow are `xn` and `e` more readable/understandable than for instance `xmlNode` and `event`?
- davelnewton 10y agoI don't think OP is claiming they're more readable in general, but for tiny scopes where they're ghosted in a line or two I'm not sure I see the point in being super-descriptive, either. (Although I wouldn't use `xn`, I'd use `node`. `e` for `event` is fine.)
- runesoerensen 10y agoHe wrote "For locals and lambdas", which includes more than just tiny scopes (where I agree that short variable names can be appropriate and improve readability e.g. `xmlNodes.Select(x => x.Value)`)
- british_india 10y agoYes. I had an application that had to interact through REST services with a second application. Three specific variables needed to be passed back and forth. Unfortunately, they were given entirely different names in the different systems so I ended up with: firstSystemNameAKAsecondSystemName Nobody was confused.
- joshka 10y agoI'd probably find that annoying in a code base. This is what the idea of a Bounded Context (See [1]) in DDD solves. Within your application's bounded context, call it whatever makes sense to your application, with an anti corruption layer to translate between the two. [1]: http://martinfowler.com/bliki/BoundedContext.html http://martinfowler.com/bliki/BoundedContext.html
- msluyter 10y agoMy general rule is that the greater the scope -- lexical or runtime -- of a variable, the more descriptive its name (which often means longer but not always!) So, for a short lived variable, I'm personally ok with it being short, as in, some random bit of python: # strip the last char from everything in a list some_list = [s[:-1] for s in some_list] IMHO, I don't really think it matters what 's' is here, and I don't think it would would be that helpful if given a more meaningful name. The cognitive load is small. Conversely, variables that live a long time and/or operate globally are better off with a longer name. However, I would observe that your example might suggest a coding issue, the tipoff being 'and'. If a single variable is handling two chunks of state, then perhaps it's doing too much and you might be better off with something like: val documentSavedOnDiskJsonStates... val pdfSavedOnDiskJsonStates Not huge savings there, but perhaps also things might get clearer encapsulating these things in a class, with methods like (just making stuff up): document = Document.getFromDisk() document.jsonStates() Not saying that this is always the correct approach or valid in your particular case, just making the general observation that IME highly modular code tends to require fewer really long names.
- amorroxic 10y agoAgree. Context is king indeed, our assertion is this: (any type of)documentAnd(convert success)PDFState(categoric variable)JsonStates(chunks of json states). It's part of an Akka Streams well, stream :) (i/o -> content transform)
- kazinator 10y agoThe greater the scope, the longer the name. But: the broader the fame/notoriety of the entity, the shorter the name! Just like in human culture. Among your friends or family, you have a nickname. In a broader situation, you might go by your first name, and in a broader one still, by your full name. But: if you're stinkin' famous, then you might get a nickname again, and everyone knows it. I'm not going to give the Lisp cons function a seventeen letter name just because it is global.
- raldi 10y agoVariable name length should be proportional to scope. Lambda parameter, or loop iterative? Go with x or i. Global variable? Make it descriptive.
- jfmiller28 10y agoGlobal Variable? Make it go away!
- NEDM64 10y agoAlways, only use x, y, z, etc. when they are descendants of the variables with big names. Because autocomplete. Really don't understand the binaries implication.
- jiqiren 10y agoObjective-C user checking in: yes.
- anupshinde 10y agoCode is for humans to read and machines to execute. So as far as it is readable, I won't change long variable names. I've used long names many times, when it is deserved. Most of the times it is longer function/method names, or constants or configuration variables. However, if a method/function is too long (i.e. too many lines in that single method/function) then it is very likely to have longer variable names within the scope and that method itself is likely to be a good candidate for refactoring. Sometimes the same applies to configuration variables (for example- stuff you read from a json config)
- omfgseriously 10y agoDuring development it is helpfull; also, if the code is not being commented thoroughly as the programming continues, the LongZOMGxVarNamesLikeThisToIllustrate variable names which have served their purpose, help in doing the commenting nicely and may or may not be shortened at that time.
- davelnewton 10y agoIt depends. I'm skeptical `documentAndPdfSavedOnDiskJsonStates` is a useful variable name. Without context it's hard to say. It sounds like you have a couple of collections of states (state names?) for various document types. PDFs are already documents, so that seems redundant. It already sounds like `savedDocumentStates` and `thumbnailStates` would be adequate--but again, without any context, it's impossible to know if that would be adequate. (Personally I'd have a type => state mapping and skip them altogether, and use a different form of classification altogether.)
- amorroxic 10y agoThere is a domain specific case indeed, would've been better perhaps to offer a bit of context: https://speakerdeck.com/amorroxic/reactive-resumes https://speakerdeck.com/amorroxic/reactive-resumes - we deal with different types of documents then pdf conversion as standard in, followed by parsing, ai, analysis.
- schappim 10y agoIf you've got a developer with previous Objective-C/Cocoa/iOS experience they'll be used to having crazy long method / variable names. You can find a list of examples here: https://github.com/Quotation/LongestCocoa https://github.com/Quotation/LongestCocoa Edit: I just had to quote the longest one: "outputImageProviderFromBufferWithPixelFormat:pixelsWide:pixelsHigh:baseAddress:bytesPerRow:releaseCallback:releaseContext:colorSpace:shouldColorMatch:"
- wingerlang 10y agoHow about this one https://twitter.com/SmileyKeith/status/758405691509911552 https://twitter.com/SmileyKeith/status/758405691509911552
- trentnelson 10y agoLongest and oldest I remember: `we_need_to_sort_interface_list` circa 13 years ago: https://github.com/freebsd/freebsd/commit/fdbb382f1cbb42ab486d1f7812f0f78c0317b799#diff-bb6d5274442cdd13b81de7e39c3368fbR249 https://github.com/freebsd/freebsd/commit/fdbb382f1cbb42ab48... Aww, looks like someone renamed it a decade later: https://lists.freebsd.org/pipermail/svn-src-head/2013-February/045058.html https://lists.freebsd.org/pipermail/svn-src-head/2013-Februa....
- skybrian 10y agoYes, this happens all the time. In some language it's more common than others. Here are some arguments against it: http://journal.stuffwithstuff.com/2016/06/16/long-names-are-long/ http://journal.stuffwithstuff.com/2016/06/16/long-names-are-...
- sp527 10y agoI end up doing this because I'm either using Eclipse or Vim + YouCompleteMe. Every programmer should get their autocomplete story in order so we can all hop on the long variable name train :)
- sethwm 10y agoA Nickel's Worth's guide on variable naming seems like a relevant read here: https://a-nickels-worth.blogspot.ie/2016/04/a-guide-to-naming-variables.html https://a-nickels-worth.blogspot.ie/2016/04/a-guide-to-namin...
- deleted 10y ago[deleted]
- partycoder 10y agothe wider the scope, the more explicit you need to get to disambiguate the meaning of something. long variable names are just a hint that your scope is too wide and a wide scope usually means: - high coupling - lack of encapsulation - action at a distance - wrong level of detail Therefore it's a code smell. Imagine we referred to each other as "multicellular organism from the kingdom animalia phylum chordata clade synapsida class mammalia order primates suborder haplohrini family hominidae genus homo species homo sapiens sapiens".
- sudeepj 10y agoI found one today in Go source code: https://golang.org/src/net/fd_windows.go https://golang.org/src/net/fd_windows.go variable name: hasLoadSetFileCompletionNotificationModes
- nailer 10y ago> documentAndPdfSavedOnDiskJsonStates 1. Why is it the document and the PDF? Are they the same thing? if so, pick one term and use it consistently. > SavedOnDisk 2. Disk is the default place to save things. > Json 3. JSON isn't an interesting label, as it gives you no ides of the data structure. If this is a hashmap with a bunch of document titles and booleans with their save status, then that should be obvious. This thing seems to be save state for multiple documents, right? So I'd replace: > documentAndPdfSavedOnDiskJsonStates with documentSaveStates or pdfSaveStates
- amorroxic 10y agoReally good perspective. Seeing the same thing on a daily basis tends to induce color blindness, plastic memory - no longer realizing difference between self documentation and meaningless verbosity. Thank you.
- joshka 10y agoTL;DR - It depends ;) The examples you provided (with some context gleaned from your other comments) look like they're probably too long and tack on unnecessary domain specific detail (e.g. jsonStates). Both variables in your example would likely be better off describing the use of the variable rather than the contents. E.g. use ageInYears rather than yearsAliveInt. Taking it to your example, perhaps something along the lines of convertedDocument would do, this is significantly shorter than your example, but perhaps conveys enough info for your ongoing usage. This is covered to in Clean Code [1]. "The name of a variable, function, or class, should answer all the big questions. It should tell you why it exists, what it does, and how it is used." The notes on the naming chapter at [2] are quite good as well (as noted elsewhere on this thread by @runesoerensen) I like to follow the principle in naming variables that if I could read the code to a non-technical user verbatim and have them understand the code, it is "good code". I.e. does reading the code out loud as a sentence make sense, or do the verbs and nouns I've chosen act as a barrier to understanding. EDIT: Ward Cunningham said that last part better: “You know you are working on clean code when each routine you read turns out to be pretty much what you expected. You can call it beautiful code when the code also makes it look like the language was made for the problem.” [1] Martin, Robert C. (2008-08-01). Clean Code: A Handbook of Agile Software Craftsmanship (p. 18). Pearson Education. Kindle Edition. https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/B001GSTOAM https://www.amazon.com/Clean-Code-Handbook-Software-Craftsma... [2] http://www.itiseezee.com/?p=83 http://www.itiseezee.com/?p=83
- gremlinsinc 10y agoI've been working on some legacy code which has been fun lately, and a lot of the functions are like get_something_one_way in one model, then another model will be like find_something_the_same_way - for instance get_store_by_slug, and find_product_by_slug -- this annoys the crap out of me... use find or get and standardize functions..everything should have a standard to make it easier to know what you're looking for.. I like to use find --when I'm querying the database, and get when I'm querying an external API or when I'm proxying an api from a model.
- hannele 10y agoBrevity is the soul of wit - I try not to make long variable names if I can help it.
- cjhanks 10y agoUsing them: Yup. Even though I only use an 80 character terminal. I prefer line breaks over having no clue what a function does/variable is. Sometimes it takes me an hour to realize the algorithm I am looking at is something I already know. Debating: Definitely. Some Java (not C-style) constructs simply require 100+ character terminals to be readable. Their community has(have not) absolutely adopted IDE's with exceptional auto-completion. 10 C++ programmers, 10 development environments (unless you have a fantastic system administrator). So for a mathematician translating their symbols into syntax, one letter is enough. A maintenance programmer understanding a legacy system...Longer names, /please/.