On Feb 16, 7:25 am, Scott Sauyet <[email protected]> wrote:
> Michael Haufe (TNO) wrote:
> >Sam Merrell wrote:
> >>     var person = {address: {zip: 1234}},
> >>          person2 = {};
> >>     console.log("Person2 undefined: " +
> >> ((person2||{}).address||{}).zip || "no zip");
>
> > Looks like a code smell of bad design. If you have a Person object it
> > would be unnecessary to do member sniffing tests and literal
> > injections like this.
> > [ ... ]
> > I'd say do this:
>
> > var person = new Person(new Address(1234)),
> >      person2 = new Person();
> > console.log(person2.zip || "no zip");
>
> I don't buy it.  Presumably you have an Address object nested in your
> Person object that itself has a `zip` property.  And if that's the
> case, you still need to reference it by
>
>     person.address.zip
>
> which could still have the problem we're trying to address, unless you
> are automatically creating empty objects for every missing property.
> I can't see what it buys us.

quack quack, it kills the ducks on creation and not on every single
attempt to access members. Presuming the structure of the object is an
implementation detail.

> I'm guessing that what Angus was suggesting with
>
> | Michael, If you've gone that far why not just have Person have a
> | getZip() method to encapsulate the null checking?
>
> is the same thing I feel:  you're trying to cram a Java/C# OO idiom
> into Javascript which more naturally deals with very dynamic data
> structures.

Organizing data is not some language dependent idiom. As you or the OP
or anyone else creates something beyond trivial code you mentally have
some notion of types and contracts in your mind. Its wiser to make
this explicit in your code using the features of the language than to
play a defensive programming game that is unnecessarily slow and
potentially verbose. There is no need for null/undefined checking on
the level being advertised here if the data structures were organized
in some manner instead of being thrown in some semblance of property/
method bags to interrogate on every use.  If by the definition of
dynamic people think it means its super 1337 cool and JavaScripty to
say:

(person2||{}).address||{}).zip || "no zip"

on every single member access, I think you are quite mistaken. Common
practice and best practice are two different things.

-- 
To view archived discussions from the original JSMentors Mailman list: 
http://www.mail-archive.com/[email protected]/

To search via a non-Google archive, visit here: 
http://www.mail-archive.com/[email protected]/

To unsubscribe from this group, send email to
[email protected]

Reply via email to