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

Elliott Sprehn esprehn at gmail.com
Tue Jan 29 10:26:28 PST 2013


On Tue, Jan 29, 2013 at 10:38 AM, Jake Archibald <jaffathecake at gmail.com>wrote:

> On 29 January 2013 05:36, Charles McCathie Nevile <chaals at yandex-team.ru>
> wrote:
> >> Exactly. And if we designed XMLHttpRequest from scratch it would have
> them
> >> too.
> >
> > Really? This doesn't seem like a good idea, so I'd be interested to know
> > why. Is there an explanation laid out somewhere?
>
> 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. It lets you structure
your code without having to worry about when something executes, and it
lets you inspect the object in the web inspector without having the verb
execute first.

For example you can do var request = new XMLHttp( .... ) at the start of a
function, but then later decide you didn't want to send the request, and
never call send(). It also lets you create clean abstractions and layers so
one library may create the notification, but another one may eventually
show it. With notifications I can't look at the properties of a
notification in the web inspector without having it show on me...

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

- E



More information about the whatwg mailing list