←back to thread

79 points ingve | 3 comments | | HN request time: 0.639s | source
Show context
mst ◴[] No.42479128[source]
> Despite this, please use volatile anyway! When I do not see volatile it’s likely a defect. Stopping to consider if it’s this special case slows understanding and impedes code review.

There are quite a few things I reflexively write where I know that in the specific case I don't actually need to do that, but also know that it'll make the code easier to skim read later.

I hate having my skimming interrupted by "is this the case where this is safe?" type situations.

One can, of course, overdo it - and to what extent it's worth doing it depends on who you expect to be reading it - but it can often be quite handy.

A concrete example:

    this.attrs = { style: {}, ...attrs }
will work fine if the 'attrs' variable is null, because ...<null> is not an error in javascript and expands to nothing ... but I'll still often write

    this.attrs = { style: {}, ...(attrs??{}) }
instead because it makes it clear that the code is allowing the null case deliberately and because it means the person reading it doesn't have to remember that the null case would've worked anyway (and also because my brain finds it weird that the null case does work so it often makes me pause even though I well know it's fine once I stop and think for a second).
replies(1): >>42480070 #
1. smitelli ◴[] No.42480070[source]
Is that vanilla JavaScript or TypeScript? I had always thought that one of the main benefits of TS is that it would probably yell about the first case. (I currently only dabble in the JS world.)
replies(2): >>42480763 #>>42485741 #
2. zdragnar ◴[] No.42480763[source]
The spread syntax is native to JavaScript. TS wouldn't complain about the first case, because as the parent said, it is a valid operation.

TS only complains about valid operations if there's some potential mistake due to ambiguity, usually when relying on to strong conversions such as adding a string and an array together or some other nonsense.

3. mst ◴[] No.42485741[source]
TS would require you to have attrs typed as object|null rather than object before you even got to that line if you wanted to be able to pass a null value to the function/whatever.

It wouldn't complain about the ... usage itself because ...null is well defined and therefore not a type error.

(it would I think complain about trying to apply ... to something that isn't allowed, though I don't recall making that particular mistake yet in TS code to find out)

Though also, trivial example is trivial - I was looking for the simplest thing that was valid code and let me illustrate the general concept.