<p>Like many programmers out there in the wild, my first real programming language was Java in University, and there were a couple pearls of programmers wisdom I kept and respected all my life. One of those is: "Use descriptive variable names. Whoever is reading your code shouldn't need to waste time guessing that h means hub and c means connection. By using bad variable names you are obfuscating your code for yourself and others without necessity because you won't waste much more time by writing a full word, specially with auto-completion." I value this rule so much that whenever some friend asked me to review their code and it included variables such as "a" and "b", I would tell them to fuck off and come back with descriptive variable names. </p>
<p>I'm not an experienced programmer nor an experienced gopher and judging at the comments, most people here know more about Go than I know about programming as a whole. However it seems like everyone uses single letter variables and I can't see a single valid reason to do so besides being lazy.</p>
<p>Are really most gophers that lazy and disregarding of good programming practices or am I missing something?</p>
<p>edit: okok, <em>familiarty</em> <em>admits</em> <em>brevity</em>. My personal anecdotal experience tells me that is a wrong statement but it's nonetheless an interesting discussion.</p>
<hr/>**评论:**<br/><br/>dominikh: <pre><p><a href="http://doc.cat-v.org/bell_labs/pikestyle" rel="nofollow">http://doc.cat-v.org/bell_labs/pikestyle</a> – Variable names in particular.</p></pre>alexfiori: <pre><p>Fun to see this paragraph:</p>
<p>"I eschew embedded capital letters in names; to my prose-oriented eyes, they are too awkward to read comfortably. They jangle like bad typography."</p></pre>dchapes: <pre><p>The single best line in that section of your link (IMO obviously):</p>
<blockquote>
<p>Indices are just notation, so treat them as such.</p>
</blockquote></pre>dchapes: <pre><p>Similar is <a href="http://research.swtch.com/names" rel="nofollow">http://research.swtch.com/names</a> (I was surprised I didn't see this link in other replies).</p>
<p>In particular, some people here seem to neglect the half of these recommendations that explicitly say that global (or otherwise rare or distant) references need to convey more information and therefore should be somewhat longer (but <code>longerDoesnotMeanEntireSentences</code> like some of the <code>examplesInThatLink</code>).</p></pre>ackondro: <pre><p>This is talked about in the <a href="https://github.com/golang/go/wiki/CodeReviewComments#variable-names" rel="nofollow">Code Review Comments</a> page on the Go wiki.</p></pre>klaaax: <pre><blockquote>
<p>This is talked about in the Code Review Comments page on the Go wiki.</p>
</blockquote>
<p>I personally totally disagree with that rule. Variable names should make the code readable.Sometimes short names do (i,j in loops) sometimes they don't (b,what is b if I don't know the context?) .</p></pre>calebdoxsey: <pre><p>It comes from "The Practice of Programming":</p>
<blockquote>
<p>Programmers are often encouraged to use long variable names regardless of context. That is a mistake: clarity is often achieved through brevity.</p>
</blockquote>
<p>In many ways this book is the design manual for Go.</p></pre>argus_the_builder: <pre><p>Do you think <a href="http://golang.org/src/bufio/bufio.go?s=12421:12490#L469" rel="nofollow">this piece of actual go code</a> (Line 523 - flush()) found in the languages source code fulfills the commitment to "clarity"? This is not an isolated case. This is common.</p></pre>usernameliteral: <pre><p>Looks pretty clear to me. Would you prefer this:</p>
<pre><code>func (writer *Writer) flush() error {
if writer.err != nil {
return writer.err
}
if writer.size == 0 {
return nil
}
written, err := writer.writer.Write(writer.buffer[0:writer.size])
if written < writer.size && err == nil {
err = io.ErrShortWrite
}
if err != nil {
if written > 0 && written < writer.size {
copy(writer.buffer[0:writer.size-written], writer.buffer[written:writer.size])
}
writer.size -= written
writer.err = err
return err
}
writer.size = 0
return nil
}
</code></pre>
<p>The original below is more readable to me. The longer names obscure the logic. It's like reading "<a href="https://en.wikipedia.org/wiki/Buffalo_buffalo_Buffalo_buffalo_buffalo_buffalo_Buffalo_buffalo" rel="nofollow">buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo</a>".</p>
<pre><code>func (b *Writer) flush() error {
if b.err != nil {
return b.err
}
if b.n == 0 {
return nil
}
n, err := b.wr.Write(b.buf[0:b.n])
if n < b.n && err == nil {
err = io.ErrShortWrite
}
if err != nil {
if n > 0 && n < b.n {
copy(b.buf[0:b.n-n], b.buf[n:b.n])
}
b.n -= n
b.err = err
return err
}
b.n = 0
return nil
}
</code></pre>
<p>Edit: Lengthened local var <code>n</code> in the modified example. (Hopefully we can agree that <code>err</code> for <code>error</code>s is OK.)</p>
<p>Edit2: I forgot to change the receiver in the declaration from <code>b</code> to <code>writer</code>.</p>
<p>Edit3: writer.written → writer.size, as it should have been (still horrific)</p></pre>argus_the_builder: <pre><p>Thank you for illustrating my point, the first option may be ugly and could be bettered but is still better than the second. Why? Because b.n is not the characters that were written, but the characters that exist in the buffer (in other words, "size"... Why not fucking call it size??). Ofc you wouldn't have failed translating/understanding the code if the code had good variable names :3 </p>
<p>Also, yes, there is no problem in calling error err or multiplexer mux, or whatever. But there is a problem when you are calling "size" "n" and written characters also "n". It's not simplicity, it's unnecessary obfuscation.</p>
<p>And why not call b "buf"?? It's so more explicit and still so short... </p>
<p>I mean, I agree, I prefer short variable names. Those java guys who write variableThatDoesThisAndThatAndThatThingAlso get to my nerves, but the opposite is also bad, that code snippet is the extreme opposite, and imo, borderline retarded.</p>
<p>Edit: My main complaint is that this is the extreme opposite of overdescriptive variable names. I should look at the function and understand it without spending 5 minutes trying to read the code. Simple 3 letter variable names and a bit longer when needed greatly simplify that task. Also, fast scrolling while reading the code is easy and possible with descriptive variable names (even if it's 3 letter variable names), but much harder when more than 50% of your variables are single letters. It's a nightmare actually.</p></pre>usernameliteral: <pre><p>Good point, but I'm not convinced. My careless search & replace, after a long day, without attention to detail should should not be misrepresented <code>Writer.n</code> is obviously not the amount of bytes that have been written, it doesn't even make sense. If I would have just looked at what the code was doing instead of trying to write a snarky comment, I would probably have realized that. That being said, I would probably have chosen <code>size</code> myself, but as they say, <em>familiarity admits brevity</em>.</p></pre>argus_the_builder: <pre><p>We are all in the internet to make snarky comments. The internet wouldn't be the same without them.</p>
<blockquote>
<p>familiarity admits brevity</p>
</blockquote>
<p>That's the problem. I hate that concept. Just because you are familiar with that codebase, that doesn't mean everyone is. Just like the other guy said in his article: I like familiarity, I like brevity, but familiarity does not admit brevity. Brevity is a propriety by it's own right that should be used whenever possible and logical. But you should never, ever abbreviate because you are familiar with it; you should abbreviate if you can and do it without the name losing it's meaning; b has no meaning, buf means buffer. Familiarity is personal, but your codebase is not personal and other persons will have difficulty to attain familiarity because of your obfuscation.</p>
<p>Just my opinion. I'll keep coding with (around) 3 letter var names and enforcing descriptive naming on our codebase. But it saddens me that the golang community has this "familiarity over brevity" approach because it makes it harder for people to get into golang, doesn't make libraries more readable and overall this aproach supposed advantages are completely overshadowed by its disadvantages.</p></pre>uabassguy: <pre><p>Yes but if b means byte and not buffer, what would you name it? byt? I'd see byt and think it may mean byte or bit if someone was trying to represent it but had a terrible habit of misspelling words on purpose just to keep things short but unique, or was forced to change bit to byt just because naming someone bit would be illegal in the stricter sense. </p></pre>argus_the_builder: <pre><p>dude... what's the issue with using 4 freakin letters... name it byte. problem solved. </p>
<p>edit: yah, byte is built in, can't name it byte. But my stance remains the same; I'm advocating to abbreviating as much as you can without stripping the meaning.</p></pre>dilap: <pre><p>A lot of it depends on personal preference, to be sure.</p>
<p>There's definitely something about our brain that let's us grasp short letters more easily <em>once you're familiar with their meanings</em>, though. Have you done much math? There's a reason everything uses hyper-condensed notation; it makes it much easier to manipulate. But there's a lot of spin up time in learning what all the notation is, and getting into the current context.</p>
<p>I think for something like the given example, where it's all private variables of the implementation, it's pretty reasonable to be brief.</p></pre>uabassguy: <pre><p>And I do agree with having non cryptic source code, I don't however feel that gophers are being "lazy" because there is a level of standardization present in go that isn't there in other languages, plus with type casting it takes out the guesswork of what a variable actually is nor does one have to inspect an object just for the purpose of type discovery </p></pre>jart1987: <pre><p><code>b.n</code> and <code>n</code> represent the same concept, number of bytes, which is why they use the same identifier. <code>b</code> is not called <code>buf</code> because it is not a buffer in the traditional sense, it is a Writer wrapper to a buffer. I have never seen this code before but it took me about 5 mins to figure all of this out.</p></pre>adiabatic: <pre><blockquote>
<p><code>b.n</code> and <code>n</code> represent the same concept, number of bytes</p>
</blockquote>
<p>Yes, but number of bytes what? That's my sticking point. It's probably obvious once I've been habituated to this, but I'm not there yet (I tend to lose nothing by using ioutil.ReadAll).</p></pre>jart1987: <pre><p><code>b</code> gives you context, number is bytes left in the buffer. <code>n</code> is declared in the code so you already know that it was number of bytes written. The part that is being missed is that names won't give you context only the code can, so stop typing to put context into names that doesn't help any.</p></pre>argus_the_builder: <pre><p>It would take seconds with better var names.</p></pre>jart1987: <pre><p>No it wouldn't, you still need to gather the context of the code to full understand it. Also the function name is flush, guess what the code is gonna do, flush the buffer.</p></pre>calebdoxsey: <pre><p>Yes. The exported names are clear. Maybe renaming <code>n</code> would make the code more clear, but it's not obvious.</p>
<p>It's common because that's the style convention. The book I referenced is worth a read.</p></pre>usernameliteral: <pre><p><a href="https://www.youtube.com/watch?v=sFUSP8Au_PE" rel="nofollow">A talk about naming by Andrew Gerrand</a></p></pre>mdwhatcott: <pre><p>...which I totally disagree with. Slides #8 and #9 are totally backwards.</p>
<p><a href="http://michaelwhatcott.com/go-code-that-stutters/" rel="nofollow">http://michaelwhatcott.com/go-code-that-stutters/</a></p></pre>jerf: <pre><p>I have to admit I'm getting "this close" to just using <code>self</code>, <code>this</code>, or even just <code>s</code> for all my handlers, yeah. It's frustrating when I refactor a name to go rename all the handlers (and naked search&replace doesn't work so good when you're renaming "a" to "c"), it's frustrating when the abbreviation comes out to one of the existing single-character names, it's frustrating when it still comes out ambiguous anyhow (i.e., two classes in the same file that abbreviate the same), it's frustrating when my class name has three words in it and I can't quite figure out how to abbreviate it... It's a whole lot of frustration for what is, as near as I can tell, zero gain in clarity over a convention for "self", and arguably <em>less</em> than zero because there is no convention now so you have to read the function declaration to tell what it's doing.</p></pre>rogpeppe: <pre><p>The receiver of a method is really just another parameter. I very often refactor code between method, function and inner block, and when doing this it really helps to have the same naming convention for all variables of the same type, regardless of whether they're local variables, parameters or receiver parameters. Then I can often just move the code without doing any variable renaming.</p>
<p>It's a pity that gofmt -r treats single letter variable names specially - it makes it less useful for one of the things that's most awkward to do in an editor.</p></pre>argus_the_builder: <pre><p>"We can use c for commit because it's obvious." Without any context referencing c is commit besides a couple calls lost in the middle of the function.</p>
<p>No it's not. I'll be honest about my opinion, don't take it personally, but what that guy is saying is borderline retarded.</p></pre>AzulRaad: <pre><blockquote>
<p>don't take it personally</p>
<p>what that guy is saying is borderline retarded</p>
</blockquote>
<p>We can understand your position without the need for any name-calling. Please don't do this.</p></pre>peterbourgon: <pre><blockquote>
<p>Without any context referencing c is commit besides a couple calls lost in the middle of the function.</p>
</blockquote>
<p>The declaration site of a variable is always pretty obvious context.</p>
<blockquote>
<p>what that guy is saying is borderline retarded.</p>
</blockquote>
<p>Obviously it's a sincerely held and considered belief. Andrew is a member of the core Go team. The rule (insofar as it's a rule) has the tacit approval of the rest of the Go team. Maybe it's not so useful to call it "borderline retarded"?</p></pre>argus_the_builder: <pre><p>yep. not useful at all, sorry for that.</p>
<p>But go read go source code. When the guys behind a language are enforcing rules that force you to spend 5 minutes understanding a function that could have been understood at a glance if it had good var names. That rule is a bad rule and creates more problems than solves</p></pre>peterbourgon: <pre><blockquote>
<p>ules that force you to spend 5 minutes understanding a function that could have been understood at a glance if it had good var names</p>
</blockquote>
<p>I don't doubt that this is your experience. But it's apparently not the experience of other perfectly capable programmers. Maybe the problem isn't the language developers. Maybe the problem is that you're too rigid in your opinions?</p></pre>jerf: <pre><p>You'd really have to post some specific examples to get a better answer.</p>
<p>One thing that Go does more of than some other OO languages is write functions that manipulate things through their interfaces. When what a function has coming in is an <code>io.Writer</code>, what are you going to call it? <code>socket</code>? <code>file</code>? You don't know what it is, so it may as well be <code>w</code>.</p>
<p>There's also a suite of more Go-specific shortcuts, like <code>w</code> for <code>io.Writer</code>, <code>r</code> for <code>io.Reader</code>, I see a lot of <code>f</code> for a file, stuff like that.</p>
<p>I also find myself occasionally using shorter or weirder names because a package took up the generic one I really want to use. The <code>path</code> module is full of great stuff for manipulating paths, but also therefore claims the <code>path</code> name for itself, so.... <code>p</code>? Guess so. You'll probably work out what <code>p</code> is when I keep calling <code>path</code> stuff on it....</p>
<p>Later edit: One thing about Go's philosophy is that generally speaking you shouldn't see that many tokens on a line anyhow. <code>n, err := w.Write(b)</code> may be full of single-character names, but once you're used to it it's all pretty standard. Now, go ask the Haskell community about how many tokens they're willing to put on a single line.... Also be sure to hook up <a href="http://godoc.org/code.google.com/p/rog-go/exp/cmd/godef" rel="nofollow">godef</a> support in your editor, which ought to make "jump to definition" one keystroke.</p></pre>rogpeppe: <pre><blockquote>
<p>Also be sure to hook up godef support in your editor, which ought to
make "jump to definition" one keystroke.</p>
</blockquote>
<p>Just wanted to point out that the canonical location of godef is now <a href="http://godoc.org/github.com/rogpeppe/godef" rel="nofollow">http://godoc.org/github.com/rogpeppe/godef</a>.</p></pre>iqandjoke: <pre><p>Is it different from cmd+shift+click on SublimeText3 with GoSublime? I am not sure.</p></pre>Betovsky: <pre><blockquote>
<p>I also find myself occasionally using shorter or weirder names because a package took up the generic one I really want to use. The path module is full of great stuff for manipulating paths, but also therefore claims the path name for itself, so.... p? Guess so. You'll probably work out what p is when I keep calling path stuff on it....</p>
</blockquote>
<p>Is this because package names have to be lower-case? Is there a reason behind why they stipulate to be lower-case instead of upper-case?</p></pre>calebdoxsey: <pre><p>It's a convention so it's mostly arbitrary, but consistency matters.</p>
<p>One way it can matter: both OSX and Windows have case insensitive file systems. If you've ever had to deal with case issues in git, it's not a fun problem. You end up just always using lower case names.</p></pre>Betovsky: <pre><p>But the issue with git/file systems is the same. The only way to avoid it is to be consistent. In the current scenario, to always be lower-case. The same applies if the convention would be upper-case.</p>
<p>If it was arbitrary, then it means that this situation only got caught at a latter process, when the convention was already established. Not a big problem, just a minor inconvenience. </p>
<p>Went to look on the documentation to found anything. They just advise exactly against path scenario <a href="https://blog.golang.org/package-names" rel="nofollow"><strong>Don't steal good names from the user</strong></a>. Maybe if the convention was upper-case this issue wouldn't happen. But then, maybe it would appear other issues, maybe clashing if there was also a struct <code>Path</code>.</p></pre>argus_the_builder: <pre><p><a href="http://www.reddit.com/r/golang/comments/3aporh/why_so_many_gophers_use_single_letter_variables/cset924" rel="nofollow">http://www.reddit.com/r/golang/comments/3aporh/why_so_many_gophers_use_single_letter_variables/cset924</a></p>
<p>Yes w.Write is quite obvious and for built in stuff I usually stick with the single letters because it's obvious. The problem lies in using single variable names indiscriminately. Like in the <a href="https://youtu.be/sFUSP8Au_PE" rel="nofollow">video</a> the other guy posted, using c as commit and saying "we can use c, it's obivous" (which it is if you read it, but isn't if you glance at the function). </p>
<p>Reading a full codebase riddled with s,p,h,sp,fs,dt,op,nb,mp variables is a nightmare. Yes, the meaning is obvious if you read the function, but when you are just "scrolling down looking for shit" it's a freaking nightmare because it forces you to read to look for context. Which imo, is very very dumb.</p></pre>peterbourgon: <pre><blockquote>
<p>Yes, the meaning is obvious if you read the function, but when you are just "scrolling down looking for shit" it's a freaking nightmare because it forces you to read to look for context.</p>
</blockquote>
<p>You should always be reading the function to understand the code. You shouldn't optimize your code for readers who are skimming at maximum speed.</p></pre>argus_the_builder: <pre><blockquote>
<p>You should always be reading the function to understand the code. You shouldn't optimize your code for readers who are skimming at maximum speed.</p>
</blockquote>
<p>That's like saying you don't need to write perfectly clear english because the reader should take his time to understand the meaning of what you wrote.</p>
<p>The code should be as clear as possible and optimized for maximum readability by anyone in any situation. It doesn't even matter if you are fast skimming.</p></pre>divoxx: <pre><p>I used to question this as well but after reading a lot of good Golang code and realizing that I wasn't having problems tracking those variables, I adopted it and now it feels natural to me.</p>
<p>The idea is that if your design is good, you'll likely not have many variables to track in a single method/function. For package variables or anything that has a longer lifetime, you'll notice that longer names are used.</p>
<p>Also, they are rarely arbitrary variables. They are usually common wide-used abbreviations, for example: n and i for numbers, the latter mostly used for array indexes and/or counters; b or buf for buffers; h for Handler, etc.</p>
<p>Also, it probably comes a bit from computer science / math background, in which single letters are used for variables, logic predicates, etc.</p></pre>klaaax: <pre><blockquote>
<p>Why so many gophers use single letter variables?</p>
</blockquote>
<p>it's wrong most of the time. It is acceptable if there is no ambiguity.</p>
<p>ex : </p>
<pre><code> func Handler(rw http.ResponseWriter, r *http.Request){
rw.Write([]byte("Hi"))
}
</code></pre>
<p>is easy to read (and more or less conventional)</p>
<pre><code> func F(x somepackage.Z,y int){
x.t(y)
}
</code></pre>
<p>Is not acceptable at all.</p>
<p>But you're implying that "gophers" write clean code to begin with, which is not true, some do , some have no clue as to what writing clean code means.</p></pre>dmikalova: <pre><p>I feel like one of the reasons is that your code should be broken into short pieces which do simple units of work. My roommate goes by the mantra that a function should be 5 lines or less, and at most 25 lines is really pushing it (he doesn't write Go code though). With such short pieces it really does make sense to use short variables because they become obvious in the context of the code and you aren't juggling 15 different variables.</p>
<p>Once those start to coalesce into large units - for example at the package level, descriptive names are great and plentiful in Go.</p></pre>argus_the_builder: <pre><p>I like your roommate...</p>
<blockquote>
<p>With such short pieces it really does make sense to use short variables because they become obvious in the context of the code and you aren't juggling 15 different variables.</p>
</blockquote>
<p>That is the theory and I agree. But if you read actual golang source code from golang itself or gorilla, you will notice single named vars being used in package wise declarations, structure parameters, everywhere. It's a nightmare and it's the freaking team behind golang encouraging this crap. </p></pre>kpmy: <pre><p>As did Pascal and Oberon earlier, Go allows to write short idents without code safety loss. </p></pre>gsscoder: <pre><p>The rule of using descriptive variable name certainly contributes to readable code.
Anyway I think that there's other two more important rules (at least to me):</p>
<ul>
<li><p>keep your functions simple, assigning one specific duty (hence composed of relatively few lines)</p></li>
<li><p>write code that doesn't need comments (excluding the ones consumed by documentation tooling).</p></li>
</ul>
<p>When your code is understandable and <strong>well partitioned</strong>, short variable (or parameter) names should not impact readability (anyway as <a href="http://www.reddit.com/user/jerf" rel="nofollow">jerf</a> said I'll like to see some example).</p>
<p>Another allowed exception could be the one of <a href="http://golang.org/ref/spec#Function_literals" rel="nofollow">lambda functions</a>. For what I see, also in various different language is common defining lambda function parameters using a single letter (and I also adhere to this most of times). </p></pre>argus_the_builder: <pre><p>I guess you and <a href="/u/jeff" rel="nofollow">/u/jeff</a> are right.</p>
<p>i and j are enough for "index", mux is enough for multiplexer and if you follow the other rules your function should be simple and have few parameters. As long as the meaning of the variable can be understood with one half a second look at the code, the name is good. I agree with that and I can see how it is logical to name a parameter with a single letter.</p>
<p>The problem is when people start using single letter vars for everything, specially global and/or "inside the function scope" vars. It's something worse than cancer in my book. Such as the m and c in the run() <a href="https://github.com/gorilla/websocket/blob/master/examples/chat/hub.go" rel="nofollow">here</a> and the h (hub) <a href="https://github.com/gorilla/websocket/blob/master/examples/chat/conn.go" rel="nofollow">here</a> (gorilla toolkit official example code). This is not a very serious scenario, I've seen worse (libraries used in production with 100 line long javascript functions kind of worse). This was just a "fuck, not again" moment, but illustrates my point.</p>
<p>edit: Besides, I do believe that if in said package you already have a "c" for "client", you shouldn't also be using "c" for "connection", even on different parameters on different functions, it's also something I've seen many times and imo unnecessary and obfuscating. If it's the same thing, same name, if it's not, different name. Regardless of the function you're in.</p></pre>gsscoder: <pre><p>The first example is not so bad... The code is clean and composed of few lines: I think they chose <code>h</code> for <code>hub</code> to avoid a name conflict of <code>var hub = hub { ... }</code>.</p>
<p>If I had written the second example, I certainly used something more expressive like <code>conn</code> for <code>connection</code>, etc.</p>
<p>Even if I can understand that you faced code with bad formatting and variable naming during your work experience (<em>I've seen a lot of horrors in mine too</em>), I think example you reported are still well understandable.</p>
<p>I agree with you that if code get complicated, you're helped from descriptive variable names. Anyway the point is that: <strong>code should be kept simple</strong>. Complexity should arise from combining simple pieces of understandable code.</p></pre>argus_the_builder: <pre><p>The big crime in that hub example is that the h is declared in another file. Big crime in my book.</p>
<blockquote>
<p>I agree with you that if code get complicated, you're helped from descriptive variable names. Anyway the point is that: code should be kept simple. Complexity should arise from combining simple pieces of understandable cod</p>
</blockquote>
<p>Totally agree. But as I said in another reply, scrolling down a file riddled with "sh" "fh" "bh" "sp" "mb" "s" "m" "f", etc ican be a frustrating exercise that could be a breeze with more descriptive names, even if you have simple code. Another issue is the using of the same letter in different context. if "m" is message, then m is message forever. There can't be an multiplexer called "m". It <em>will</em> confuse the reader sooner or later, specially if the repetition happens in the same file/package.</p>
<p>But this example of <a href="http://golang.org/src/bufio/bufio.go?s=12421:12490#L523" rel="nofollow">actual golang code</a> (line 523 - flush()), similar to the one found on <a href="http://michaelwhatcott.com/go-code-that-stutters/" rel="nofollow">this article</a> someone shared in this post perfectly illustrates my frustration. That piece of code is simply not legible. Period. It's bad, really bad and I would be ashamed if it was code written by me.</p></pre>oliver_newton: <pre><p>i'm okay having short variable names as long as they're within the same routine, or at least within the same file.</p>
<p>when i started coding, there's no such thing called autocompletion. i also happen to be involved in OpenBSD project where, at some point, we have to kill lots of whitespace and also replace long variable names in order to make small binary size. but at the same time, we have to make sure our peers understand the code we wrote. </p>
<p>i'm pretty sure most of Go developers came from similar background. so calling them lazy for naming short-length variables without knowing the history... is kinda harsh.</p></pre>hobbified: <pre><p>Because that's a pretty lousy rule. Variables that are referenced in a small scope should have useful but <em>short</em> names. By keeping the semantic content of the variables small you give your brain less things to process, which makes it easier to understand the code as high-level chunks. It's stuff that's externally visible that needs to be named well. And even there, <em>good</em> naming isn't necessarily the same as <em>verbose</em> naming. If you have a library that revolves around one or a few central concepts, I would rather you gave those concepts short distinctive names (especially in Go where anything from another package is going to be used with qualified names anyway).</p></pre>argus_the_builder: <pre><blockquote>
<p>Because that's a pretty lousy rule. Variables that are referenced in a small scope should have useful but short names. </p>
</blockquote>
<p>Agree. But having 50% or more of your code comprised of single variable names is more challenging to your brain than having descriptive variable names. I mean, 3 letter vars guys...I'm not asking for javaVariableWithARidiculousLongName. I'm asking for buf instead of buffer, msg instead of m, conn instead of connection. </p>
<p>Clear fucking names. </p>
<p>I was just now discussing the flush() function in <a href="http://golang.org/src/bufio/bufio.go?s=12421:12490#L469" rel="nofollow">here</a>. Notice on how the b.n which is basically the size of the buffer has 0 context and has the same name ("n") than the characters written... Why, god, why? :(</p>
<p>I love the language, but I simply hate this one letter culture.</p></pre>gohacker: <pre><p>I for one do find short variable names in the stdlib not less but more readable.</p></pre>ar1819: <pre><p>Go compiler and surrounding tools have some code style guidelines, but nobody forces you to use them in your own projects. Actually many people prefer camelCase naming in their own packages.</p>
<p>To be fair, camelCase has its flaws - its adds sufficient amount of "dots" for your eyes to recognize and create text in your mind. It takes even longer to read code properly. While it can be better for new team members, the old ones - who are already familiar with codebase, are actually getting tired of reading this "containerIndex" variables. They know what n stands for and that shortage helps them understand and code faster.</p>
<p>But at the end of the day, its just the matter of personal preference. And Go, as language, even with go fmt, doesn't force you to any specific variable naming, so you're free to choose whatever you like. I never seen any github Issue about renaming variables in go projects.</p>
<p>For anyone who thinks differently - look at docker or camlistore or cayley code. The last one even mixes shot one and camelCase.</p>
<p>P.S. This "Worship of the gods" is beginning to be really disturbing. Go creators sad, that they created Go for practical reasons, and language HAS flaws. It's not perfect, it's not supreme - it's just a good and simple tool for writing applications. Yet, I still see people, who use famous "go community" names like its supposed to be ultimate answer to ANY question. We are engineers here or what? </p></pre>ducttapedude: <pre><p>Holy cow, Argus. I'm reading these comments as a primarily C#/JS dev, and I don't understand why everyone is defending unreadable code.</p>
<p>Maybe I need to read golang more, but the arguments of "that's what comments are for" and "you'd understand what b.n is if you read the entire function and Writer documentation" or "anything except lowercase burns my soul" are entirely unacceptable.</p>
<p>Variable names are a tool for the developer. The runtime doesn't particularly care. If this is the kind of crap that the golang community and its libraries cultivate, my interest is waning.</p></pre>argus_the_builder: <pre><blockquote>
<p>If this is the kind of crap that the golang community and its libraries cultivate, my interest is waning.</p>
</blockquote>
<p>Exactly how I'm feeling. This shit is people ignoring 30 years of wisdom for no practical reason at all. </p>
<p>Edit: I guess they feel that because go is very idiomatic, you can be less idiomatic in your coding style.... imo, you can't. And if I'm your boss, you fucking won't.</p></pre>velco: <pre><p>You, guys, aren't really helping your point with words like "shit", "fucking", "crap", "retarded", "freaking team", etc.</p>
<p>I'm pretty sure there are several core Go people with more than 30 years of
... wisdom accumulation under their belts. ;)</p>
<p>Instead of fighting it, why don't you try this approach in your own projects? Try to make readable code with short or one letter variable names, no matter if in the beginning it'll make you puke. Who knows, you may find code clarity is not that directly (if at all) related to length of local variable names ...</p>
<p>And if this experiment fails, well, nobody can really force any guidelines upon your own projects.</p></pre>mdwhatcott: <pre><p>Simply put, it's laziness.</p>
<ul>
<li><a href="http://michaelwhatcott.com/familiarity-admits-brevity/" rel="nofollow">brvty</a></li>
<li><a href="http://michaelwhatcott.com/go-code-that-stutters/" rel="nofollow">go code that stutters</a></li>
</ul></pre>velco: <pre><p>Use comments to describe what is what. Don't try to encode the said comments in variable names.</p></pre>argus_the_builder: <pre><p>"The proper use of comments is to compensate for our failure to express ourselves in code"</p>
<p>Are you saying that we don't need to write self-explanatory code because we can explain in comments? Well, I'm sorry, but I have a very contrary opinion and I won't change it anytime soon: if you need to look at a comment to understand a piece of code, the code is bad. Good comments explain why the programmer made a decision, not what the code does. </p>
<p>Tool generated docs for api documentation is obviously a very different scenario.</p></pre>velco: <pre><p>"The proper use of comments is to compensate for our failure to express ourselves in code"</p>
<p>This can be said by someone who has never encountered a piece of non-trivial code. I regularly read entire books or multi page articles, which explain why and how a particular algorithm works.</p>
<p>PS. Besides, I've clearly written "what" and not "how". </p>
<p>The comment should be the answer to "what".
The code itself should be the answer to "how".
If it's simple enough.</p></pre>argus_the_builder: <pre><blockquote>
<p>This can be said by someone who has never encountered a piece of non-trivial code. I regularly read entire books or multi page articles, which explain why and how a particular algorithm works.</p>
</blockquote>
<p>Most programmers work with trivial code. That generalization applies to trivial code. You can't expect regex voodoo and complex sorting algorithms to be self-explanatory, no one is saying that. </p>
<blockquote>
<p>The comment should be the answer to "what". The code itself should be the answer to "how". If it's simple enough.</p>
</blockquote>
<p>Slightly disagree.</p>
<p>Variable/function names, and if they are not enough also Class/package/function comments, answer "what". Code itself answers "how". "In-code" comments answer "why". Again, more complex code is an exception, but again, most programming is not complex algorithms, most programming is just tying together a couple libraries made by someone else.</p></pre>klaaax: <pre><blockquote>
<p>Use comments to describe what is what. Don't try to encode the said comments in variable names.</p>
</blockquote>
<p>it goes against clean code's philosophy, code should be "self explanatory". and yes even complex algorithms can be reduced to functions with readable names. </p></pre>velco: <pre><p>Appeal to authority.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传