4 ms·
Interesting, but the JavaScript examples hurt: let table = [ ['one','two','three'], ['four','five','six'] ]; let b = document.body;
by skerit 1y ago
Interesting, but the JavaScript examples hurt:
let table = [
['one','two','three'],
['four','five','six']
];
let b = document.body;
let t = document.createElement('table');
b.appendChild(t);
table.forEach((row,ri) => {
let r = t.insertRow(ri);
row.forEach((l,i) => {
let c = r.insertCell(i);
c.innerText = l;
})
});
Use full words for variable names!
- niek_pas 1y agoI was just about to comment the same. I’m sure people have a good reason for it (or at leafy _a_ reason), but single-letter variable names always struck me as optimizing for the wrong thing. As someone who likes to program in Haskell, I feel this pain very strongly. :)
- bottd 1y agoDo you always feel this is the case? To me the go to single letter variables are very readable. Used so widely my eyes parse them like other symbols: =, &, +, etc.
- alentred 1y agoMy rule of thumb: only using single letter variables in one-liners (and never if it spills to another line), or for something that is conventionally represented as such. So for example: ```python bar = [foo(e) for e in elements] ``` or, using `x`, `n`, `s` and similar when they represent just that, a generic variable with a number, string, etc. I think there is a Code Complete chapter about it.
- jazzypants 1y agoYeah, I'm not GP, but my exceptions to this rule are `i` for "iterator" in `for` loops and `e` for "event" in event listeners.
- NetMageSCW 1y agoDon’t use ‘i’ (looks like 1), use ‘j1’, etc - helps set you up if you need a nested loop someday. Of course, at that point better naming would probably be best.
- adamddev1 1y agoStrong BASIC memories. On the Apple IIe, anything after the first two characters of variable names was ignored.
- croes 1y agoIn real ok, but in this short example it‘s pretty obvious what t,b, r and c mean
- somat 1y agoIt is also a math thing. most(if not all) constructions intended for mathematical consumption have some of the most miserable naming I have ever seen. I think it comes down to two things. when I am feeling less charitable it is that naming things is hard. so they don't bother. And when more charitable it is that they are optimizing for quick mental manipulation of a familiar machine. This tends toward the smallest variable names you can get away with, tons of implied context and compressed symbology. Of course this leaves the rest of us struggling, not with the concept but the way it is presented. I like to joke, "you think programmers are bad at naming thing, you should see the mathematicians, programmers are infants before the infernal naming sense of the common mathematician".
- ninjin 1y agoReally? The variable name lengths? Not that the code is clearer as: const te = document.createElement('table'); document.body.appendChild(te); [ ['one', 'two', 'three'], ['four', 'five', 'six' ], ].forEach((r, i) => { const re = te.insertRow(i); r.forEach((c, j) => { re.insertCell(j).innerText = c; }) }); My personal stance on short variable names is that they are fine as long as their scope is very limited, which is the case here. Rather, the "crime" to me is an overuse of rather pointless variables as the majority of them were only used once. Disclaimer: I have not tested the code and I only write JavaScript once every few years and when I do I am unhappy about it.
- matt_kantor 1y agoLooks like your code inserts a new row for every cell.
- ninjin 1y agoCheers! Fixed.
- jonathrg 1y agoThis is not an improvement. Having named variables for things is good actually. They will need to be declared again immediately once you want to modify the code. insertCell(i).innerText = c is a nonsense statement, it should be 2 lines for the 2 operations
- ninjin 1y agoI disagree, but maybe it is a cultural thing for those of us that are more used to functional styles of programming? I was taught method chaining as a style by a seasoned JavaScript and Ruby programmer myself and I do not find the semantics confusing. "Create X with Y set to 17 and Z to 4711" can be either on one or three lines to me, as long as the method calls are clear and short enough. As for variables, I (again personally) find it taxing to have many variables in scope, so I do net see their presence as a universal good. If we instead simply use expressions, then there is no need to concern yourself with whether the variable will come into play later on. Thus, I think it increases clarity and favour that over the ease of future modification argument you propose (heck, I would argue that you get better diffs even if you force the variable declaration into a future modification). As for bikeshedding this piece of code further, if I steal some ideas from chrismorgan [1] and embedding-shape [2] who appear to be way more seasoned JavaScript programmers than me: const $t = document.createElement('table'); for (const r of [ ['one', 'two', 'three'], ['four', 'five', 'six' ], ]) { const $r = $t.insertRow(); for (const e of r) $r.insertCell().innerText = e; }; document.body.append($t); This is now rather minimal and the logic is easy (for me) to follow as the scopes are minimal and namespace uncluttered. It was a rather fun little exercise for a language I am not overly familiar with and I learned a few tricks and perspectives. [1]: https://news.ycombinator.com/item?id=45782938 https://news.ycombinator.com/item?id=45782938 [2]: https://news.ycombinator.com/item?id=45781591 https://news.ycombinator.com/item?id=45781591
- AlienRobot 1y agoPersonally I'd make everything const instead of let and use for of instead of forEach, but it's like 10 lines of code it doesn't really matter.
- Sharlin 1y agoAre you sure this old API does the right thing with for…of?
- kaoD 1y agoIt's only used to iterate the array
- Sharlin 1y agoOops, right, I confused the variables.
- runarberg 1y agoShould work just fine: > document.createElement("table").rows[Symbol.iterator]() // Array Iterator { constructor: Iterator() } HTMLTableElement.prototype.rows actually just returns a HTMLCollection, so same as document.forms, or document.getElementsByClassName. HTMLCollection implements Symbol.iterator as you would expect. https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement/rows https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableEl...
- layer8 1y agoA bike-shedding thread on top as usual.
- poisonborz 1y agoCode quality is not bike shedding.
- Sharlin 1y agoIt is, however, off topic and beside the point. And whether short names are a code quality issue is a rather contested and context-dependent topic.
- nkrisc 1y agoCode quality of... an example snippet?
- davidmurdoch 1y agoEspecially
- blackcatsec 1y agoespecially now that the example is gonna end up in some LLM somewhere and folks will just copy pasta.
- refulgentis 1y agoUsually I'd cosign, but I get it, after a similiar issue I had a couple days ago with a Rust article that was insanely frustrating to deal with. It's a brain scramble because you can't just read in toto. Well, you can literally, but, you don't feel like you grok it. And when you take a second pass you gotta slow down and stop and parse "what's r here? is it relevant? oh rows?" It's one of those things that's hard to describe because it doesn't sound like much if you got it. And this example is trivial, especially if you're not open to the idea its a problem (r/c = rows/columns) But it's nigh-impenetrable in other scenarios. You feel like you're barely understanding something that you actually might grok completely.
- phoronixrly 1y agoLooks to me like it's following the JS conventions... Jk, no such thing exists still!!
- Sharlin 1y agoIt’s normal to use short names for things with short scopes.
- foofoo12 1y agoYes, and the reason for why that's OK is that the context is just few lines. But this is borderline due to the amount of variables. In just 4 lines you have r, row, t, ri, l, i and c. The full variables names are so short anyway that personally I'd write them out. Code does evolve and there's a risk of this suffering as a result.
- Sharlin 1y agoThat’s a fair point.
- NetMageSCW 1y agorowIndex isn’t that short.
- bdangubic 1y agoshortness is in the eye of the beholder… program with spring framework long enough and rowIndex sounds like abbreviation. :)
- foofoo12 1y agoRowIndexFactoryGeneratorService rowIndexFactoryGeneratorService = new RowIndexFactoryGeneratorService(); RowIndexFactory rowIndexFactory = rowIndexFactoryGeneratorService.getTheFactoryOrSomethingIDontCare(); RowIndex rowIndex = rowIndexFactoryGeneratorService.generateRowIndex();
- foofoo12 1y agoWe might be able to use rowIx? Let's discuss it on the next Monday standup. Everyone will need to have an opinion, max 5 minutes per person.
- shiandow 1y agoI think the short names aren't anywhere near as bad for readability as using (ri,i) as a table index. If you're going to use short names at least make it clear which belong together. Especially don't use different lengths when things ought to be similar. data.forEach((row,i) => row.forEach((ele,j) => ... ))
- jfengel 1y agoIt's the lets that bother me. The point is elderly JS, and the entire operation is fundamentally imperative. But this code is brimming with opportunities to make mistakes. JS deserved its reputation.
- fsckboy 1y ago>Use full words for variable names! that's like saying in spoken language "don't ever use pronouns, or even first or nicknames, use full given names"
- groguzt 1y agoyou are being intentionally dense, they are saying "don't use a single initial to identify someone, use their firstname instead"
- fsckboy 1y agoI'm being dense? dense is something I never am, though pithy I will take. here, read this, and then you try to write something equally persuasive about long variable names. I'll wait https://cgtweb1.tech.purdue.edu/courses/cgt456/Private/Readings/hunganotat.htm https://cgtweb1.tech.purdue.edu/courses/cgt456/Private/Readi...
- egorfine 1y ago> let b = document.body; This one hurts the most. Save a few bytes for an ungodly amount of mental friction.
- tbrownaw 1y agoIt doesn't save any bytes, that variable is used once.