[whatwg] [Notifications] Constructor should not have side effects

Ian Hickson ian at hixie.ch
Tue Jan 29 11:28:38 PST 2013


On Tue, 29 Jan 2013, Elliott Sprehn wrote:
> On Tue, Jan 29, 2013 at 10:38 AM, Jake Archibald wrote:
> >
> > Why doesn't it seem like a good idea? Is there a use-case for creating 
> > a Notification/XMLHttpRequest/WebSocket/EventSource without performing 
> > their action?
> 
> Yes, because decoupling allocating from action lets you preallocate 
> objects to perform a task in advance of executing the task.

As a JS author you really shouldn't be worrying about pre-allocating 
stuff. Let the browser decide how to optimise for that. The browser is in 
a better position to know whether it's better to optimise for memory 
usage, creating objects at the last minute, or whether it's better to 
optimise for speed, with objects pre-created and ready to roll when the 
script invokes them. It's possible that objects like this will be hosted 
in a pre-allocated arena, where the construction cost is essentially free, 
so that there's no advantage to doing it ahead of time in the JS. It's 
also possible that the system is seriously memory-constrained, so that the 
allocation should only be done if it is absolutely necessary. It's 
possible that the browser isn't really going to allocate anything at all 
because it has a highly-optimised primitive for this type of object, so 
that changing the object from "undefined" to a constructed "WebSocket" 
object will require no more than changing a few bits in the underlying 
value (e.g. because the networking layer doesn't hold much state for these 
objects, and therefore holds it all in a pre-allocated data structure 
which the JS interpreter just needs to index into).


> With notifications I can't look at the properties of a notification in 
> the web inspector without having it show on me...

What properties would you want to look at?


> Constructors are not verbs. new Notification doesn't mean "show", and 
> new XMLHttpRequest doesn't mean "send".
> 
> This is pretty standard OO best practices stuff. ex. 
> http://www.beaconhill.com/solutions/kb/java/code-in-constructor-anti-pattern.html

That post asserts this, but provides no reasoning for it.

-- 
Ian Hickson               U+1047E                )\._.,--....,'``.    fL
http://ln.hixie.ch/       U+263A                /,   _.. \   _\  ;`._ ,.
Things that are impossible just take longer.   `._.-(,_..'--(,_..'`-.;.'



More information about the whatwg mailing list