[Javascript] Object reference usage (was Javascript and FF)

Mike Dougherty msd005 at gmail.com
Mon Aug 31 13:54:07 CDT 2009


On Mon, Aug 31, 2009 at 1:32 PM, Paul Novitski<paul at juniperwebcraft.com> wrote:
> look-up repeatedly, but it sounds like you're looking for something
> more authoritative than a 'common sense' opinion.

I'm looking for discussion to hear multiple sides of the issue - so
thank you for your commentary :)

> My take on this subject pertains almost entirely to bulletproofness.
>
> I realize that your example is deliberately forced and isn't likely
> to appear in mature code as is, but it brings up a stylistic flaw I
> see in lots of code out there.

Absolutely agreed.

> I endeavor always to test for the existence of an object before
> referring to its children. Here's a hypothetical example that grabs
> the content of the second paragraph in the header of a document:
[example snipped for brevity]
> I work like this to make my code durable and easy to read and modify.
> It does end up that I use a lot of transient variables to hold
> objects during the drill-down, and I certainly hope that I'm not
> hosing the processor by doing so. I've never experienced any
> perceptible latency by coding in this way, but then my JavaScript
> usage tends to be light touches and not long involved applications
> that might more likely challenge the processor if JavaScript doesn't
> create temp variables efficiently or the heap if garbage collection
> isn't up to snuff.

  I also learned to code defensively and do preemptive checking for
errors because earlier languages didn't give much choice, you either
tested for bad input or you faced ugly run-time problems.  However,
consider how much extra code your example required to test every step
down the path.  To some, that extra verbosity isn't exactly readable.
  How do you feel about the approach: assume success but handle failure?  ex:
try{
  var var sContent =
document.getElementById('header').getElementsByTagName('p')[1].firstChild.nodeValue
}
catch(err){ alert("Something unexpected happened - developer
assumption failure") }

The user is probably not interested in all the ways the assignment
could fail, they only need to know that it did.  Under normal
conditions there is no need to do all the preemptive checking because
the script was written for a known DOM structure.

I'm on the fence.  I can see the advantage to both approaches.  I can
also see how both are abused.  I have a coworker who writes code like:
 try{ main(); } catch(err){ alert("broken!") }  with no other error
handling.  :)



More information about the Javascript mailing list