Why do libraries not expose classes?
You can look at winston as an example: the createLogger function is just a wrapper around a constructor. Why is this done, rather than just exposing the class? (DerivedLogger isn't the best name for a publicly-visible class, of course, but that's easily changed.)
Posted Aug 9, 2018, 10:21 PM UTC
In case they decide not to use a class in the future. Or more generally, so the library author is free to change the implementation at any time, by keeping the surface area of the public API small and designed for backwards-compatibility.
Sounds like everyone in this entire thread has just been speculating. This is the commit where winston made that change. They say it was to take advantage of V8 optimizations. The idea in that commit seemed to be to create a new class on the fly for each call to createLogger, and attach the logger levels to that class's prototype rather than to the instance. I'm dubious whether this really achieved an optimization (it sounds like it should do the opposite), but, nonetheless, you wanted to know their reason why, and this is it.
cc u/ViKomprenas
This doesn't actually reduce the API surface, though, does it? I can still get at the class fairly easily with
.constructor. It's straightforward on their part to remove that path (delete X.prototype.constructor), which is why I didn't think it was for forwards compatibility, and still don't think they did a good job -- even of communication -- if that was their intent.(Nor can I really imagine a scenario where it wouldn't be preferable to use a class for this, or any other example I've seen, although obviously how comfortable to be with that is very subjective.)
API means the intended functionality. You can usually get through to implementation details via runtime functionality, but that doesn't mean you should rely on that. It's usually not worth the trouble to try to hide these things from the user, but they're still not intended to be used.
A documented language feature with no mark that it's for internal use (underscores, for instance, a la Python) is unintended functionality? I'm genuinely surprised.
Does JavaScript allow you to do it? Yes. Does winston say anything about what
winston.createLogger().constructoris? No. Then it is not part of the winston API.You should not rely on any behavior of
winston.createLogger().constructorin the same sense that you should not rely onwinston.createAwesomeLoggerbeingundefined, or (if you want to get extreme)winston.createLogger().constructor.toString()[6]being'D'