10 ms·
> Doesn't it introduce a weird (stateful!) computation that's hard to reason about? Yes and no. For example, maybe you want to initialise a temporary directory
by diatone 5y ago
> Doesn't it introduce a weird (stateful!) computation that's hard to reason about?
Yes and no. For example, maybe you want to initialise a temporary directory on the filesystem for writing files to, for some caching mechanism. The pointer to the cache directory (maybe a const x = {}) can exist anywhere, but spinning up the directory itself in the static class block ensures that it's set up once and only once for all instances of the class. So, any instances get to reuse the directory without worrying about checking for initialisation first.
Just another tool in the toolbox, best evaluated on a case-by-case basis
- IshKebab 5y agoThat's a pretty terrible example. No way do you want temporary directories to be created just by loading a class. That violates all sorts of best practices. There's a better example here: https://v8.dev/features/class-static-initializer-blocks https://v8.dev/features/class-static-initializer-blocks You could also use it for initialising generated constants.
- ricardobeat 5y agoWhat’s the difference from declaring the entropy pool in the example outside the class, in the module scope? Still private, still a single shared value.
- IshKebab 5y agoI think just scope (same reason static class members exist).