196 points · by migueldemoura · 8y ago · 164 comments
I carry over the same principles to functions/methods. Functions are usually less than a screen which makes it rather easy to pick up the context and understand the program flow and the use of variables. I use "list" if there is there is a single list. The context usually defines what is in there. Maybe the function name, the type declarations or the fact that we are in a part of code handling lists of customers. How hard is it to guess what countCustomers(list) or incrementCustomersScore(list, n) is doing? Writing incrementCustomersScore(goodCustomerList, customerScoreDelta) is just redundant. Variable names just need to be descriptive enough to define their role within it's context. If the function is very small, the variable names can be very short.
Local variables are the smallest named things in our systems, whith a very small scope, there shouldn't be an excessive naming cult around it. Give advice how to properly name projects, packages, namespaces and classes and I start listening. We are really bad at this.
When you're as jaded as I am, very.
What is list? What are its elements? Is it a list of customers? Is it a list of something that has a customer as one of its properties? I've seen far too much bullshit in my time to make any contextual assumptions about something called "list".
Same goes for "n". Is that the number of customers whose scores to increment, or is it the amount to increment for each customer in the list? Or something else? What happens if it's negative?
Any time I have to look inside a function (no matter how small) to see what it actually does, I find myself wondering why I must endure this extra cognitive load (and then endure again later when I read the same code but have forgotten the implementation details). And any time I find even mildly ambiguous names, I MUST assume the worst, because people just do stupid things, and therefore I must assume for my own survival that YOU have done stupid things, even if you haven't.
It's very little extra effort to call it modifyCustomersScores(customers, scoreDelta) and eliminate as much guesswork as possible.
Remember: Code is read FAR more often than it is written. Why wouldn't you take steps to optimize throughput on the common path?
Explicit naming is a courtesy. It's developer U/X. It's telling your reader "Yes, I've been there in the trenches. I've seen the horrors. Here's a flashlight to help you on your way."
But even code rot can be mitigated somewhat with this discipline.
Which of these changes is easier to justify:
countCustomers(list)
incrementCustomersScore(list, n)
// where "list" is to change type from "list of customers" to "list of sales domains"
VS countCustomers(customers)
modifyCustomersScores(customers, scoreDelta)
// where "customers" is to change type from "list of customers" to "list of sales domains"
Code is a map to what the computer is supposed to do. Making things familiar and easily navigated just makes sense. Good code requires good U/X, just like good websites require good U/X. It's just something you do to make your users have a better time using your stuff.Local type inference ("var") can reduce the friction here, but, you've probably still got to explicitly declare types for parameters and return values, so there's always an excuse to be lazy.
I'd say that full-on Hindley-Milner type inference might help, except that I suspect that the folks who do this kind of thing would find a way to create even more chaos in the kinds of languages that have one.
I would invest effort in making the definitions of local variables easy to read, while keeping the names short. (And keeping the functions themselves short so there aren't many locals in scope.)
The idea is to reduce cognitive load as much as possible for someone navigating your code. Every line the reader has to read increases cognitive load, and slows him down.
Using `list` is just bad. Your list (probably) holds a set of things that has a name. So name your list that. At the very least, name it after the type of things it's holding. Types are only declared once, but variable names are forever. Having to constantly look up the type of a variable because the programmer was too lazy to name the list of things as `things` instead of `list` is rather inconsiderate.
(Of course, there are times when you would use `list`. For instance, if you're writing a list sorting function, and you actually have zero context more than "yep, this thing is a list".)
As you say, list might be the best name for a variable if the use context is generic. The same with iterators and such. But you really have to think ahead to keep the names consistent, complicated names work against consistency.
List<Foo> foos;
for (fooIndex = 0; fooIndex < foos.length; ++fooIndex) {
Foo foo = foos[fooIndex];
List<Bar> bars = foo.bars;
for (barIndex = 0; barIndex < bars.length; ++barIndex) {
Bar bar = bars[barIndex];
}
}
It would be immediately, visibly obvious if you accidently use `fooIndex` in the `bars` list. Good luck getting that with `i` and `j`.That, of course, is assuming you even need the indexes. Otherwise you get this:
foreach (Foo foo in foos) {
foreach (Bar bar in foo.bars) {
}
}Thre's strong grounds for saying that `i` is better.
At least in a lot of the code I work with, `index` is most likely to be assumed to mean something akin to a SQL index similar - a data structure or module used for fast lookup.
Whereas `i` is universally understood to be an iteration counter or a position in a sequence. That's a well-known convention that goes back for hundreds of years, and that many (if not most) of us learned before we really learned to program, by virtue of its use in math notation.
And yes, words can have many definitions. This is where you actually do rely on context for the reader to separate. And I have zero issues with local conventions overriding global conventions. So if you really do have a lot of confusion between whether an integer means an array index or an SQL index, by all means create convention to disambiguate.
(Also, while "hundreds of years" is technically accurate, it's probably not as old as you think. Euler was mid 1700's with his sigma summation notation.)
"Oh, great... Here's another `list` variable, let me go see what it is this time."
lst is actually a very good example. If you are writing small functions of less than a screen (which you arguably should be), and you can see that lst is a list of FileInfo, and the code to populate it in a function called GetAllWebConfigsUnderPath, and you have twenty of thirty other types of list generating functions, then seeing lst as the primary thing that gets filled everywhere is comforting and recognisable.
Having said that, having lstWebConfigs and lstAppleFiles and lstUnixFiles might be useful, for example.
Also, I assume you mean "type" as in "the kind of things that it is", rather than its actual type, such as integer, string, etc. lstInteger is largely pointless in this age of IDEs, but lstUserIdentifiers is demonstrably better (You shouldn't compare UserIdentifiers with StockCodeIdentifiers unless you work in H.R.)
"Your list (probably) holds a set of things that has a name. So name your list that."
Also, by not including semantic information in the variable, it also requires this to be conveyed everywhere else e.g. your function names. You rightly point out that hopefully there's tight context around this thing (e.g. it's only about customers) and maybe you can leave that out, but over time as code changes and grows in weird ways, this may not always hold.
What do you think?
Won't other people still need to read private code?
It does help one turn a bad API into a bad API that will lead to slightly less bugs.
The correct comparison is: 1. what is the cumulative time wasted when people guess wrong? 2. what is the cumulative time spent writing out a meaningful name?
When I'm conservative in my estimate of how good people are at guessing my intuitions, I always find that #1 seems to dwarf #2.
like iFoo, or listFoo, etc... When using these, I often dont know whats an Object that cannot be changed, and whats a variable.
Sure you can play around with it, but I feel like I've lost plenty of time trying to understand other's code.
Are you getting paid by least amount of characters typed?
“Fewer characters” seems to be the domain of people who place little to no value on good tools. In the worst cases they make choices that are actively hostile to anyone else using better tools.
See also the Toxic 10x-er, who is really a 3x who makes everyone else 2/3rds less effective.
I realize that with time, functions like `malloc` become second nature, but why not call it `allocate_memory`? (bash suffers from this too) It's even worse when reading the source code of old video games due to the abstract nature of the operations being performed on virtual representations of visual elements.
The argument of time constraints when authoring doesn't hold much value. Java is verbose AF but it's also one of the most used languages. Second, most code is read, not written and should be written to be read by others, not just the author.
There may be a reason to be terse due to time constraints and lack of IDEs/autocomplete or memory constraints or w/e, but the need to shorten variables names and functions today only serves the whims of the author, not the 10+ future readers. tinyrant :D
As to why it happened in the first place: it is from an era when some compilers only looked at the first 8 characters for uniqueness of a name. Toss on top of that that a screen was only 80 characters wide and short names made a lot sense.
Now it is just tradition, I feel, more than anything else.
There are still developers that insist on code only ever being 80 characters wide, even in today's world of 24+ inch, 1920x1080+ monitors.
I understand wanting code to be narrow enough to be able to have diffs side-by-side, but you can get 120-character wide lines and still achieve that.
I've seen others argue that if a line is too long, it's harder to understand what it's doing, and I would agree with that with one caveat: In this context, "line length" should be understood as the number of operations being done, not necessarily absolute number of characters. A line that is 110 characters long but has meaningful variable and function names is going to be easier to grok than a line with only 60 characters but has terse names.
Regarding variable names, it's a matter of taste, but for example:
NumberOfDocumentsProcessed += MaybeFindUpdatedDocuments(ClientPool->GetClient(NextClientIndex++));
n_docs += find_updated_docs(cli_pool->get(next_cli_idx++));
I find the second line much more pleasant to read, especially if these variable names repeat several times in a function, which they usually do. The problem with long lines is that the style inevitably drifts toward the first example, because nobody can say no to "Can we make the names more descriptive?" With 80-character limit there's a certain friction that acts as a counterbalance.Resolution is largely irrelevant. The size of the font and screen size/distance is what matters for readability.
Think in terms of books that are pleasent to read. If the lines are too long it’s easy for some to lose track of where they are. If the font is too small people with poor eyesight will have trouble reading anything. Character limit is an accessibility issue. I am personally limited to ~80 characters for my use case.
Though the issue is largely irrelevant for people who are know of therecent AST aware formatting tools that can limit lines to whatever length you’d like.
I know when I was in my CS program in the early 90s it seemed like that was transitioning. The older profs would teach us every trick in the book to reduce the actual file size & visual noise in our code. The younger profs would beat in our head to not do that.
Map<K,V> drives me nuts. Especially since K has to be comparable and/or hashable.
I'd be going with `userAge` or `user_age` either way. :-P
It still is; there is a reason people tended to shorten terms in the field they are deeply engaged in. Verbosity gets in the way, and there is always a tension with it (and where the optimum point for clarity is depends on the focus and expertise of the audience.)
(in fact, some of the best keyboards I've ever used were of the old mechanical-switch variety found on IBMs, teletypes, and various CRT terminals. Even the worst of the bunch were a lot better than the almost-legendarily-bad macbook keyboard I'm using at this moment.)
> then... (and this is the kicker) when you write the code, for each of these paragraphs you write a corresponding global function named:
> Act1_2_4_6_3_13()
> Do not document these functions. After all, that's what the design document is for!
Ideally, your company will also have several file shares into which old and unidentifiable documents are filed, in nested layers of folders named things like "Old documents", "John's Code", "Please Clean Up", and "Maybe Delete". However, for maximum effectiveness do not file your design documents here! Instead, put various old drafts (not identified as such, of course) in a folder on the server where your code used to run, somewhere like C:\backups\aurdbcl1\C\Documents and Settings\users\jdoe\Desktop\ (where aurdbcl1 is the name of the server where your program ran 20 years ago). This will ensure that they will spend as long of a time as possible hunting for something that could be useful. If possible, also ensure that there are some multi-Gigabyte zip files scattered about which have to be unpacked just in case there's something useful inside.
A related technique for compiled languages is to arrange for various copies of the source code to be copied into similarly diverse locations. Do not use version control under any circumstances; if you must, check in at most once a month with the comment "changed code". This works best for a program which is maintained very rarely. Anyone attempting to fix it will first have to identify which copy of the source code is the right one. Make sure you also have some copies that never made it to production, where you started changing things and never finished. If possible, the production version should also be subtly different from all copies of the source code that can be found.
(The above is, unfortunately, from experience. I have many other rants which similarly belong in this document, particularly around exception handling and copy-pating, but I feel that this comment is becoming too long already.)
1. Write a CAD system. User-facing code in BASIC. Rendering engine written in assembly.
2. Run the interpreted BASIC code through an optimizer, which condensed all variable and function names to be as short as possible (one or two characters) and moved frequently-used routines to the top of the module before compiling it all into one executable chunk (no more interpreter). This optimized code is almost unreadable but executes a lot faster (25%-50%) than the human-readable interpreted code. Hurray!
3. Lose the original source code.
Build machine's hard drive died. The backups weren't. No version control -- only occasional snapshots. Source code that was on various floppy disks lying around the office was incomplete and badly outdated (like the "Old Documents/John's Code example, above).
4. Team panics and spends a month trying to piece "Humpty Dumpty" (the software) back together again. No luck.
5. Spend the next year trying to reconstruct function and variable names from "AA423()" and "aa_237" to such gems as "customerListIThink", "doesSomethingToInventory()", "NoIdea()", "BreaksWhenIChangeIt()" while struggling to add new features at 1/10th the rate before the loss.
6. Try to rewrite the whole thing in C.
7. Go out of business.
True story.
For a second there I thought i was reading about golang[1].
* Single letter var names[2] / [3]
* Underscores [4] / [5]
* extended ascii code [6] / [7]
[1]https://golang.org/doc/effective_go.html
[2] https://github.com/Droogans/unmaintainable-code#single-lette... [3] https://github.com/golang/go/wiki/CodeReviewComments#variabl...
[4] https://github.com/Droogans/unmaintainable-code#underscore-a...
[5] https://golang.org/doc/effective_go.html#blank
[6] https://github.com/Droogans/unmaintainable-code#extended-asc...
They are also a Haskellers favorite.
There's a non-sarcastic paper running on the internet named something like "descriptive variable names considered harmful". Most of the community agrees with it, including me.
There are tons of those in Android framework code as well
> It took a team of maintenance engineers nearly 3 days to figure out that this whopper variable name described a const, reference, function argument that was holding information from a database column of type Varchar[30] named "LastName" which was part of the table's primary key.
- const, reference and function argument should be pretty obvious from the code context
- LastNameCol seems like self-describing... of course you would have to know that you're debugging an application that talks to databases, but eh
I'd say it's somewhat akin to proving a negative. Sure you get that it's a const, reference and function argument which likely refers to the Last Name Column. However is that all it is? Or is there more meaning in the name? Meaning that could be crucial to understanding how the application functions? Does one of the characters mean function reference or does it refer to something else? Apparently not in this case but how can you know without investigating?
It’s like when you find a nil-guard in a function. You can’t truly refactor it until you know whether it was added defensively just-in-case or whether nils can still exist in the system at the function’s callsite, calling for further upstream examination.
There’s a certain hell in trying to follow a code base where every function is infected with ‘if (!arg) return’.
Fortunately, he stopped programming and became very successful in agriculture. Good outcome for both fields.
Well that is what agriculture is all about.
https://quoteinvestigator.com/2016/12/30/not-malice/
I can offer as corollary to the article a couple of unmaintainable simple batches:
http://reboot.pro/topic/2986-yacbfc-dec2hexcmd-and-hex2deccm...
This one is good and there's no attribution problem.
Only have one struct with a member of every type. That one struct will be the type of every variable you have.
If the language you use support implicit operator overload abuse them to make sure all types can be implicitly converted to each other.
Ex.
struct Variable { byte a; short c; int d; long e;
...
}This will make it impossible to know what type a variable is until you find its assignment, which of course isn't on the same line as the declaration and even better reuse the same variable for multiple values.
typedef union { int i; float f; double d; long l; char c; void *p; ... } var;
Now you might also get some nice float-interpreted-as-int bugs if you forget the type!
You can also kind of pretend that you have C#-style type inference:
var x = { .i = 10 }; var y = { .f = 2.0f };
Prefer APIs over data.
Start with DSLs.
Always connect (and never enqueue).
Create abstractions for information.
Use static typing across subsystem boundaries.
Put language semantics on the wire.
Write lots of unit tests.
Leverage context.
Update information in place.
C++ has member variables (which this refers to) and member functions.
"Method" is not part of the vernacular.
This doesn't make sense on so many levels. Only a recluse sitting in some dungeon who never dealt with people can come up with something so inane.
Edit:
I understand that that every developer should aspire to become someone who writes code that reads like a children's book, and they should. However, actively discouraging writing comments is so wrong on so many levels.
At the last place I worked, we used to have a small at-home coding test before interview and none of the young developers who successfully completed the test did any sort of code documentation or commenting. When I asked why, they would tell me that their code is self-documenting, which was utter nonsense.
Would you really argue in favor of something like this?
``` class Account { ... /// returns the accountId public int d_nr() { ... } } ```
``` class Account { ... /// returns the accountId public int getAccountId () { ... } } ```
The first comment is obsolete when using a proper method name, the second does that and so the comment is redundant.
May I ask: What did you experience in the wild?
All you have accomplished really is to move the descriptive name from the variable's name to the variable's type, and at what cost? You now have to create a whole new datatype. The programmer must look up that datatype and see oh, it's just an int. And now you need conversion routines or worse yet casting to convert that type to a simple int for interop reasons (database, UI).
Experience has shown that it is very productive to have a small number of generally useful datatypes which are augmented by custom datatypes.
Creating a new datatype for something as simple as an int or String defeats that and makes it more cumbersome to work with. (It's especially unwarranted for a variable that is an immutable variable serving as a simple id.)
That's because some document generators will exclude functions that doesn't have document attached.
At the last place I worked, we used to have a small at-home coding test before interview and none of the young developers who successfully completed the test did any sort of code documentation or commenting. When I asked why, they would tell me that their code is self-documenting, which was utter nonsense.
I see this in practice WAY too often... Heck, I've been somewhat guilty of it myself before.
(Bonus points if it's in a functional language :P )
Also, I've been led to believe that design of constrained / embedded systems follow different rules. Your code can be unreadably complex if you have to squeeze out that extra performance (however, even then, it should probably be well-commented or well-documented), and generally (though not alway) such programs will be smaller and made by smaller teams.
It's when these kind of practices are applied in enterprise software with large number of programmers, where maintainability is more important than performance, that this is an issue.
What is meant by that statement? Is "idempotent" a mistype/mistakenly selected word? If the author meant "pure" instead, should I file a PR, or consider this some sort of meta-meta-obfuscation? If the author meant "pure", is that actually true of C specifically, or just generally good programming advice (localize side effects to known locations, the fewer the better, don't sprinkle them all over and document where they occur)?
f(f(x))=x
assuming f is a function (binary operators are just functions (maps) in mathematics, too, e.g. +:NxN->N (read: "plus" is a map from the Cartesian product of N by N to N))
At the very least it should be presented in a more unmaintainable way.
Edit, apparently repo owner already checked with author: https://github.com/Droogans/unmaintainable-code/issues/3 :+1:
Grey/Gray gets me every time.
I (American) was working previously on a project with a British-spelling team for a British-spelling client. It was fine when they had named a variable and I could follow their lead, but there are so many random words with spelling differences that I’d never think of that there was invariably a bit of mix-and-matching between spelling conventions.
It’s not like I’m going to look up every word in a British English dictionary to see if I’m spelling it the British way.
GrEy for England, grAy for America.
Also, use synonyms for common function verbs. Like Grab instead of Get. GrabPageFromServer()
In a code base I dealt with, a developer did exactly those. Most "get" functions had "get" at the end of the function name. Some functions had it at the beginning, but replaced with "grab".
Also, he misspelled a class name and just went with it.
https://github.com/Droogans/unmaintainable-code#a-real-life-...
i for an index is ok, but this is a red herring: You only ever need an i for imperative iteration and in a sufficiently high level language you are better of with selection and projection, (iteration for that matter), where you just foreach over each element and don't actually need to ask for things by index. Sure, y'all be hacking C, nothing wrong with that, it depends on what you str doing, but for comprehension, the mere existence of i is a red flag, because most of the time you want something to happen to a collection if things and foreach is perfect for that (or map, fold, filter, pick your poison).
Still, a better example than `i` for short identifier names would be x,y,z, or r,g,b These are so common and conventional that I would expect them to have semantics of their own, still they could be chunked to types such as Coordniate, Location, or Point, or Paint, or Color, respectively. But comming up for better names than x,y,z is really difficult, will bloat your code and make it hard to understand what is going on.
I am pointing this all out, because many of you seem to favor such very short identifier names - and I am with you: sometimes they make sense, see above - but empirical evidence suggests that very short identifier names, and single-letter identifier names in particular significantly worsen comprehension of code. The same is true for abbreviations (depending on how strongly you abbreviate).
[1] https://ieeexplore.ieee.org/document/7884623/ (disclosure: author)
[2] https://doi.org/10.1007/s11334-007-0031-2
[3] http://compscinet.dcs.kcl.ac.uk/JP/jp040302.abs.html
[4] https://dl.acm.org/citation.cfm?doid=382080.382628
[5] https://link.springer.com/article/10.1007%2Fs10664-018-9621-...
Preprint for [1] here: https://brains-on-code.github.io/shorter-identifier-names.pd...
[5] is the extended Version of [1] including discussion of how attention is shifted during the experiment. It turns out that, when code uses words as identifier names people don't need to read the comments as much.
I've noticed this especially true for JavaScript and Go.
In JavaScript , because the language is still evolving and there is no real standard about how to architect code with this language unless you are using a entire "platform" like Angular / Vue / React witch will highly influence your coding style.
In Go because Go developers are performances obsessed , coming from C/C++ background and do believe that naming their variable with one letter will save 1GB of memory allocation , 1000 CPU Cycles and make their code "Clear and Concise"
Ultimately , because there is very little standard in this industry in terms of code governance and a large percentage of projects are outsourced to other companies , we end up with what is described in this repository.
Go is also not performance obsessed - else it would not have opted for garbage collection by default.
As far as variable naming goes, Go convention says - the further from its declaration a variable is used, the more explicit and qualified the name should be to disambiguate it. This to me strikes as being eminently sensible.
The problem is that you get too close to the code you write, and make assumptions about its obviousness that simply aren't true. Far better to be explicit at the cost of a few extra keystrokes.
data.reject{|e| e.value.nil?}
data.reject{|element| element.value.nil?}
I would always prefer the first one. My general rule of thumb is: If a variable has the scope of exactly one line, or if it is an incremental counter, use one letter.