HighDots Forums  

RFD: How To Recognize Bad Javascript Code

Javascript JavaScript language (comp.lang.javascript)


Discuss RFD: How To Recognize Bad Javascript Code in the Javascript forum.



Reply
 
Thread Tools Display Modes
  #61  
Old   
Randy Webb
 
Posts: n/a

Default Re: RFD: How To Recognize Bad Javascript Code v0.2 - 01-02-2008 , 11:18 AM






Thomas 'PointedEars' Lahn said the following on 1/2/2008 11:06 AM:
Quote:
Randy Webb wrote:
Thomas 'PointedEars' Lahn said the following on 1/2/2008 9:13 AM:
2. Using "href:javascript"

should be changed into 'Using href="javascript:..."'.

The "better example" should be

a href="myhouse.jpg"
onclick="showPicture(this.href); return false;"
Look! My house!</a

which would demonstrate that graceful degradation does not imply
double maintenance.
And an even better solution would be:

a href="myhouse.jpg"
onclick="return showPicture(this.href)"
Look! My house!</a

It was a better solution where a popup window was involved. But it would
require an additional explanation of the return value of showPicture(),
which is why I did not propose it.
If it is going into a "Bad Code" document then shouldn't you endeavor to
show the best possible way to do it? And that is why I said that I
thought that a Best Practices document is a better way to go than a Bad
Practices document. The Best document can have an end to it, the Bad
document can never ever cover all the bad code you might (and probably
will) encounter on the web.

--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ - http://jibbering.com/faq/index.html
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/


Reply With Quote
  #62  
Old   
Richard Cornford
 
Posts: n/a

Default Re: RFD: How To Recognize Bad Javascript Code - 01-02-2008 , 12:49 PM






Anthony Levensalor wrote:
Quote:
Thomas 'PointedEars' Lahn posted :

This is an excellent tip, thanks!

It's a recipe for disaster. Whenever you use scripts that use
try..catch as-is, compilation will fail with a SyntaxError.
Compilation of the other scripts, that you use along with them
and that don't use try..catch, is not guaranteed.
Maybe not guaranteed but it has generally been observed that a syntax
error in the contents of one script element (or in a resource imported
by a single script element) does not interfere with the successful
interpretation/compilation of syntax error free code in other script
elements (or imported by other script elements) within the same
document. Any cited examples where it did would be important, but in
their absence this seems excessively paranoid.

Quote:
It does not matter at all whether script A uses features that
are defined in script B, compilation is done in order of
inclusion. Since loading script resources dynamically is
error-prone, the best thing you can do for now is a) to
avoid try...catch entirely or -- where that is not
possible or feasible, such as in XHR scripts -- b) to
use eval to hide it, what I proposed.
If there is no guarantee that a syntax error at any point will not have
a negative impact outside of the particular interpretation/compilation
process (or, given that there is no guarantee, this is being assumed to
be a pertinent issue) then eval-ing potential syntax erroring code could
only be employed once per document as there must be no guarantee of the
ongoing consequences in the event of the syntax error actually occurring
when tried.

Quote:
I did some more reading after I posted that, actually, and
I was starting to come to that same line of thought, albeit
not with any real confidence. Thanks for the tip, I think
I'll avoid them entirely for the time being and use another
method for making sure my code isn't going to bomb.

As a Java developer, try/catch/throw/finally were staples
of my existence, and I naturally transitioned that. But,
as has been said many, many times here, Javascript is
not Java.
Go back 4-5 years in the archives and the general advice would have been
never to use try-catch outside of the known/controlled environment of an
intranet. But there eventually does come a point when newly introduced
features start to seem viable in the general web context.
Try/catch/finally have been part of the language specification since the
turn of the centaury (more than half of the total existence of
javascript) and it is extremely unlikely that any new JS engines will be
created without some form of sensible handling for the construct. So any
residual compatibility issue is really just in relation to very old web
browsers; mostly the forth generation of browsers and their antecedents.

(However, note that it has been suggested that IE 5 supported this
construct, but in reality JScript 5.0 did not include any support for -
finally -, and is very slightly off-standard in its support for
try-catch (though not in a way that would be problematic in normal
situations).)

On the other hand, javascript's try/catch construct is nearly totally
useless (non-practical) for various reasons. The first of which is the
way in which it must be used.

In Java (and other languages with good exception handling support) you
can be very specific about which exceptions you catch and handle (and so
will be letting any exception that cannot be handled propagate). While
in javascript you have no choice but catch every exception that is
thrown. That means that having caught your exception you then have to
work out if it was the exception you were planning to handle and if not
re-throw it.

That then introduces the second problem with javascript's try/catch,
which is identifying exceptions. There are some things that the
language's specification does allow you to determine from an - Error -
object, and in some cases that will include the necessary information
needed to identify the Error. One of (or a combination of) the Error's -
constructor - or - name - properties should allow for the identification
of the type of Error object, at least for the exceptions thrown as a
direct result of correct implementation of the language's specified
algorithms (which might broadly be categorised as "NativeErrors"). The
problem is that knowing that a caught exception is, for example, an
instance of "ReferenceError" does not really pin down which error it is
you are handling (unless the code in the - try - block is so restricted
that there is only one point where a "ReferenceError" could be thrown.

This comes to the question of the Error's - message - property. In
reality messages are usually fairly explicit about what exception has
been thrown (and often where), but not in any standardised way. The
specification for the message property says "The initial value of
Error.prototype.message is an implementation-defined string" and never
gets more specific than that. And as a result no two browsers can be
expected to produce the same message in association with the same
exception. Indeed, any single browser with a language configuration
option may not produce the same message given two differing language
configurations (they are, after all, messages to the programmer and
might reasonable be presented in the programmer's specified (possibly
native) language given a script engine author with an appreciation of
the role of language in human culture).

And if the specified - message - property is not going to help identify
individual Error objects then any implementation specific 'errorNumber',
'description', or other non-specified properties of the Error object are
going to be of even less use.

That is all just with language specified exceptions and the resulting
Error objects. Next we have the browser and the DOM both being likely to
throw exceptions in response to executing javascript code. The W3C DOM
defines a DOMException interface with a - code - property that could be
used to identify the type of an exception thrown by the DOM. Except that
in reality DOM implementations throw other exceptions, such as some
Opera 7 versions throwing a "NOT IMPLEMENTED" error when a particular
method was called (which the DOM specification asserted should not throw
an exception at all when called), and the W3C DOM specifications provide
no code number for "NOT IMPLEMENTED" (indeed they could not as the DOM
modules, as specified, are an 'all or nothing' game, regardless of the
reality of many browsers having 'good enough' but incomplete
implementations).

But then there is the browser itself, which can throw any exception it
likes ("out of memory", "too much recursion", "permission denied") and
no matter how many 'name', 'message', 'description', 'type' or 'number'
properties such Error objects may have you are going to have a hard time
identifying any of those. At best you would be looking at a trial and
error process of provoking possible exceptions in known browsers and
recoding their 'unique' characteristics and then writing code that test
for them. A process that is as incompliable as attempting to create a
comprehensive browser sniffing system based upon object inference.

So javascript's try/catch implies the need to catch all exceptions and
then identify the exception caught to see if it is an expectation that
can be handled, and re-throw those that cannot be handled. But the
ability to identify exceptions is so limited/problematic that you would
be hard pressed to find any single example of anyone actually coding
this. And indeed the mass of code that would then necessarily appear in
every - catch - block would be so obviously excessive as to tip anyone
off that any genuine exception handling in javascript was a nightmare to
attempt.

As a result what you usually see are empty (or pointless: 'alert('Some
sort of script coded f**k-up that you, as a user, can do nothing
sensible about has happened');') - catch - blocks, sometimes (but by no
means always) followed by some code to test for the consequences of the
caught and suppressed exception having been thrown (such as checking to
see an expected XML HTTP request object does exist after the attempt to
create it).

This style of try/catch use can be practical but its sensible
applications are very few and far between. Indeed it is characterised by
your usually only seeing a single statement being executed inside the -
try - block so the potential expectations thrown at that point are
extremely limited in range. So obviously any attempt to apply such a
style on a larger scale would virtually have every statement inside its
own - try - block, and result in the inverse of the nightmare of trying
to identify exceptions in order to handle them.

Thus, one web application I work on has well in excess of 100,000
statements in its client side code, is designed for use where the
browser(s) is(are) specified and so support try/catch/finally, yet in
all of that there are just 4 tiny try/catch blocks. A general strategy
of defensive programming, where potential exception throwing conditions
are test for up-front and so never provoked is the best strategy for
avoiding all of the issues with try/catch. Of course that is probably
easier to implement for those of us who were doing this 4-5 years ago
when any use of try-catch on the public Internet was pretty much out of
the question.

For completeness, there is still potential for using try/catch in
javascript, and particularly when designing large/complex systems (which
maybe is not such a good idea with javascript as a language to start
with, but anyway ...). It would be reasonable to design a system that
made heavy use of its own exceptions, while pretty much ignoring any
other exceptions. If you are creating and throwing your own custom
exceptions you can guarantee that those expectations do carry enough
information to allow for their easy identification, and so allow for the
sensible handling of those exceptions (but only those exceptions) when
they are thrown. I have never had a desire to do that myself, but if a
system was designed from day one to use such an internal exception
handling system it could be completely justified, effective and reliable
(and certainly in a browser restricted context).

Finally, there definitely is a down side to showing the use of try/catch
to novices in that they sometimes latch onto them as a universal
panacea, wrap everything they write in try/catch blocks and so suppress
all errors. This leaves their code 'error free', in one sense (the sense
of showing errors to the user) but it results in code that is virtually
impossible to maintain because if it is ever observed to be 'not
working' (which is not at all unexpected under the circumstances) then
it is virtually impossible to work out why.

So any discussion of indictors of bad code can validly mention the use
of try/catch because many specific patterns in its use are very
indicative of bad code.

Richard.



Reply With Quote
  #63  
Old   
Anthony Levensalor
 
Posts: n/a

Default Re: RFD: How To Recognize Bad Javascript Code - 01-02-2008 , 02:10 PM



Richard Cornford said:


Quote:
So any discussion of indictors of bad code can validly mention the use
of try/catch because many specific patterns in its use are very
indicative of bad code.

I just want you to know I read the whole thing. Thanks for the
informative post.

~A!


Reply With Quote
  #64  
Old   
Dr J R Stockton
 
Posts: n/a

Default Re: RFD: How To Recognize Bad Javascript Code - 01-02-2008 , 02:53 PM



In comp.lang.javascript message <pan.2008.01.02.01.12.23.424426 (AT) yahoo (DOT) sp
am.me.not.com>, Tue, 1 Jan 2008 20:26:47, Jeremy J Starcher
<r3jjs (AT) yahoo (DOT) spam.me.not.com> posted:

Quote:
The page lacks any link to a site home page or similar.

By design. I don't have a personal home page nor do I have a computer
related page anywhere. The page is hosted on a work server with
permission.
H'mmm - perhaps there should be a standard icon, looking in part like a
broken link, for "Homeless"; it would stop people continuing to look for
a Home link. But, if you add any pages, you could call that one Home.


Quote:
I don't like the idea of liberating the chlorine from one or two grains
of salt - when being clever, one needs also to be right.

With a "rule of thumb" it is much harder to define "right." In practice
I strongly discourage use of document.write. In practice, I use it
sparingly.
You may have missed the chemical point.


Quote:
"Permission granted to reproduce in any form ..." - Unwise. Copies
that are not updated are a disservice to their readers. Google for
exactly "other critical date lists at Cinderella" to see what I mean.

I will Google for that later. Do you have a licence template that you
recommend?
No. But you can see what my Home Page says. You might find it better
to say nothing more than the standard copyright reminder.

--
(c) John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v6.05 MIME.
Web <URL:http://www.merlyn.demon.co.uk/> - FAQish topics, acronyms, & links.
Proper <= 4-line sig. separator as above, a line exactly "-- " (SonOfRFC1036)
Do not Mail News to me. Before a reply, quote with ">" or "> " (SonOfRFC1036)


Reply With Quote
  #65  
Old   
Randy Webb
 
Posts: n/a

Default Re: RFD: How To Recognize Bad Javascript Code - 01-02-2008 , 02:56 PM



Dr J R Stockton said the following on 1/2/2008 7:14 AM:
Quote:
In comp.lang.javascript message <4IidnY9-v9gXG-faRVn_vwA (AT) giganews (DOT) com>,
Tue, 1 Jan 2008 13:30:25, Randy Webb <HikksNotAtHome (AT) aol (DOT) com> posted:
Is this a good use of eval?
function convertToDecimal(fraction){
return eval(fraction)
}

Where fraction is a fraction that you need converted to decimal? It can
be written like this:

function convertToDecimal(fraction){
var numerator = fraction.substring(0,fraction.lastIndexOf('/'))
var denominator = fraction.substring(fraction.lastIndexOf('/')+1)
return (numerator/denominator)
}
... or with .split("/") - but why last Index?
Simple example. My second post about it, in reply to David, shows the
actual code I used in the post where I asked about this specific issue.

Quote:
If that string is supplied from outside, then the case is already
covered as "not known at run time". Return.
Define "supplied from outside". The string is supplied as the value of a
select element.

Quote:
Otherwise, no : it is not a good use of eval.

Evidently the argument 'fraction' is intended to be a string. But a
string is not a good way of representing a fraction internally.
It is when it is the value of a select element.

Quote:
A rational fraction should be represented as {Num:n; Den:d} or similar, or
as a case of {Typ:F; Num:n; Den:d}, or as a simple case of a structure
designed to hold general expressions (a tree for arithmetic notation; an
array or list for RPN).
Or a simple string. KISS.

Quote:
It is only bad data design that makes the use of 'eval' seem appropriate
for that purpose.
It isn't bad data design at all. When you need a number in two forms -
both decimal and fraction - and you choose which one to use where, the
best way is to keep the fraction as a string and convert it to decimal
when needed.

--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ - http://jibbering.com/faq/index.html
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/


Reply With Quote
  #66  
Old   
Dr J R Stockton
 
Posts: n/a

Default Re: RFD: How To Recognize Bad Javascript Code - 01-02-2008 , 03:00 PM



In comp.lang.javascript message <8331b1ee-5f11-4391-bdc6-05d427912e5f@e2
6g2000hsh.googlegroups.com>, Tue, 1 Jan 2008 16:35:16, David Mark
<dmark.cinsoft (AT) gmail (DOT) com> posted:

Quote:
Another reason to minify is
that compression (when available) will only reduce comment bulk,
whereas minification eliminates it.
ISTM wrong always to use something that eliminates all comment, even on
a fully-commercial page not intended to be read. Comment explaining the
code should be removed; but comment identifying the source and date can
be worth retaining.

Perhaps the language should be extended with a convention that comment
to end of line which starts ////, and/or other comment which starts /**
(and finishes **/ ?) should be retained by minification.

--
(c) John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v6.05 MIME.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/&c., FAQqy topics & links;
<URL:http://www.merlyn.demon.co.uk/clpb-faq.txt> RAH Prins : c.l.p.b mFAQ;
<URL:ftp://garbo.uwasa.fi/pc/link/tsfaqp.zip> Timo Salmi's Turbo Pascal FAQ.


Reply With Quote
  #67  
Old   
Dr J R Stockton
 
Posts: n/a

Default Re: RFD: How To Recognize Bad Javascript Code v0.2 - 01-02-2008 , 03:09 PM



In comp.lang.javascript message <477B9C04.7010406 (AT) PointedEars (DOT) de>, Wed,
2 Jan 2008 15:13:24, Thomas 'PointedEars' Lahn <PointedEars (AT) web (DOT) de>
posted:
Quote:

Unfortunately, your From and Message-ID headers still violate Internet
standard STD11/RFC2822, sections 6.2/3.4 and 4.6.1/3.6.4. Please fix that.

Have you considered consulting a good craniotomist?

--
(c) John Stockton, Surrey, UK. ???@merlyn.demon.co.uk Turnpike v6.05 MIME.
Web <URL:http://www.merlyn.demon.co.uk/> - FAQish topics, acronyms, & links.
Check boilerplate spelling -- error is a public sign of incompetence.
Never fully trust an article from a poster who gives no full real name.


Reply With Quote
  #68  
Old   
David Mark
 
Posts: n/a

Default Re: RFD: How To Recognize Bad Javascript Code - 01-02-2008 , 03:46 PM



On Jan 2, 5:04*am, Thomas 'PointedEars' Lahn <PointedE... (AT) web (DOT) de>
wrote:
Quote:
Anthony Levensalor wrote:
David Mark posted :
Certainly there are mobile devices (and other agents) using script
engines that do not parse try-catch clauses. *A good rule of thumb is
to relegate the use of try-catch to scripts that you can afford to
lose in such browsers. *In other words, if you have enhancements that
will work in virtually any browser (e.g. form validation), don't lump
them in with or make them reliant upon scripts that feature try-catch
clauses (e.g. Ajax, Flash.) *That way agents that ignore the scripts
with try-catch clauses can still make use of the other enhancements.

This is an excellent tip, thanks!

It's a recipe for disaster. *Whenever you use scripts that use try..catch
as-is, compilation will fail with a SyntaxError. *Compilation of the other
scripts, that you use along with them and that don't use try..catch, is not
guaranteed. *It does not matter at all whether script A uses features that
That is outrageous nonsense. The script(s) with try-catch will not
parse. Other scripts in the page that do not use try-catch will be
fine as long as they do not rely on the ones that do. If you wish to
be overly paranoid about it (which you apparently do), you can order
the try-catch scripts last.


Reply With Quote
  #69  
Old   
John W. Kennedy
 
Posts: n/a

Default Re: RFD: How To Recognize Bad Javascript Code - 01-02-2008 , 05:57 PM



Gregor Kofler wrote:
Quote:
John W. Kennedy meinte:

Wrong on all counts. You need to find yourself a better dictionary.
"Deprecate" means to belittle; "depreciate" means to reduce the value
of. The Latin *root* of "deprecate" means to pray to be protected
from, but that is not its English meaning, properly or otherwise.

ACK. Well, as a non-native speaker I don't have the insights of JWK... I
have to rely on dictionaries.

That /is/ its English meaning -- its only English meaning until the
early 20th century when, as I said, some moron got the two words mixed
up. The fact that modern dictionaries perforce have to acknowledge the
mistake doesn't change that.

So what? Names, meanings, words have changed throughout centuries
because of errors in translation or simple typos. Being a percevtive
person, you've probably realised that the year is 2008. (You should move
to Iceland - their language hasn't changed over the last thousand years.
Well, at least only very slightly.)
I don't complain when someone uses the word "deprecate" to mean
"depreciate", because that battle was lost long ago.

But I /do/ complain when someone insists taking it further, and saying
that /only/ the mistaken use is permissible.
--
John W. Kennedy
"The whole modern world has divided itself into Conservatives and
Progressives. The business of Progressives is to go on making mistakes.
The business of the Conservatives is to prevent the mistakes from being
corrected."
-- G. K. Chesterton


Reply With Quote
  #70  
Old   
John W. Kennedy
 
Posts: n/a

Default Re: RFD: How To Recognize Bad Javascript Code - 01-02-2008 , 05:58 PM



Doug Miller wrote:
Quote:
In article <477af72e$0$13875$607ed4bc (AT) cv (DOT) net>, "John W. Kennedy" <jwkenne (AT) attglobal (DOT) net> wrote:
Doug Miller wrote:
In article <477ae913$0$13902$607ed4bc (AT) cv (DOT) net>, "John W. Kennedy"
jwkenne (AT) attglobal (DOT) net> wrote:
Thomas 'PointedEars' Lahn wrote:
a. The word you were looking for is _deprecated_, not "depreciated".
Actually, "depreciated" is the correct word. Some moron about 75 years
ago decided that "deprecated" sounded more kewl, and got the two words
hopelessly confused. Properly, to deprecate something is to pray to be
protected from it, ee.g.:
Wrong on all counts. You need to find yourself a better dictionary.
"Deprecate" means to belittle; "depreciate" means to reduce the value of. The
Latin *root* of "deprecate" means to pray to be protected from, but that is
not its English meaning, properly or otherwise.
That /is/ its English meaning --

No, it's not. It may have been at one time, but that is not its meaning now.
....this proves nothing but that your reading is restricted.

--
John W. Kennedy
"But now is a new thing which is very old--
that the rich make themselves richer and not poorer,
which is the true Gospel, for the poor's sake."
-- Charles Williams. "Judgement at Chelmsford"


Reply With Quote
Reply




Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off



Powered by vBulletin Version 3.5.4
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.