Questioning WeakMap.prototype.clear

Claude Pache claude.pache at gmail.com
Wed Jan 23 00:54:49 PST 2013


Le 22 janv. 2013 à 22:34, David Bruant <bruant.d at gmail.com> a écrit :

> 
> Back to weakmaps, the issue here is not technical, but... cultural I would say.

Indeed, the issue is cultural. We are questioning WeakMap.prototype.clear, because some people think that WeakMap should provide some strong encapsulation. But it need not be so.

The core problem is that WeakMaps are not *designed* as a secure feature. They are just designed as, well, weak maps, that is maps that don't prevent garbage collection of their keys and values. As such, they are not intended to be more (or less) secure than Maps or any other feature, but just less memory-leaking, which is very different. It is true that weak maps provide some degree of encapsulation if you don't want to expose GC,  but this is just a side-effect of the definition. It is also true that a WeakMap without "clear" method provides some strong sort of encapsulation, but this is a limitation of the API, not a an inherent property of weak maps.

By contrast, Private Symbols are precisely designed to provide good privacy. Any feature that would threat that privacy (e.g., an Object.deleteAll() functionality which wipes all own properties of an object, even those whose keys are unknown Private Symbols) is dubious. This is because Private Symbols provide privacy by *design*, not by side-effect or by limitation of the API.

If you want strong encapsulation, then either WeakMap considered as "weak map" is not sufficient, or the feature is misnamed and should have been called, say, ProtectedMap.

—Claude


More information about the es-discuss mailing list