Code Guidelines

80 views
Skip to first unread message

Garrett Smith

unread,
Dec 21, 2009, 6:52:55 PM12/21/09
to
I'm putting together a couple of documents:

1) code guidelines
2) code review guidelines

The goals are to help make for better code reviews here and to help
debate on assessing javascript code quality.

I'd like to start with my outline of code guidelines and get some
feedback on it.

Rich Internet Application Development Code Guildelines (Draft)

Problems:

Markup:
* Invalid HTML
* sending XHTML as text/html
* xml prolog (cause problems in IE)
* javascript: pseudo protocol
* Not escaping ETAGO.
Replace: "</" + "script>"
with: "<\/script>";
Replace: "</td>";
with: "<\/td>";

CSS:
* invalid css
* classNames that do not have semantic meaning

Script:
Variables:
* Global variables
* Undeclared variables
* non-descriptive name

Methods:
* initialization routines that loop through the DOM
* methods that do too much or have side effects
* long parameter lists
* non-localized strings
* inconsistent return types
Methods should return one type; returning null instead of an Object
may be a fair consideration.

Strategies:
* Modifying built-in or Host object in ways that are either error
prone or confusing (LOD).
* Use of non-standard or inconsistent ecmascript methods (substr,
escape, parseInt with no radix).
* Useless methods, e.g.
goog.isDef = function(val) {
return val !== undefined;
};
Instead, replace useless method with typeof check:
if(typeof val === "undefined"){ }

Strings:
* use of concatenation to repeatedly (repeatedly create and
discard temporary strings)
Instead use String.prototype.concat(a, b, c) or htmlBuf.push(a, b, c);

Loops:
* Loop body uses a long chain of identifiers
Replace long chain of identifiers with variable.
* Loop body traverses over elements to modify the style or event of
each element.
Solution:
Styles: Replace a loop that applies styles to descendants by adding
a class token to the nearest common ancestor and add a style rule to
the style sheet with the selector text of #ancestor-id .descendant-class.
Events: Use event delegation.

Statements:
* Use of == where === should be used
* Boolean conversion of Host object (sometimes Error-prone)
* Boolean conversion of value that may be falsish, e.g. if(e.pageX)
* useless statements (e.g. typeof it == "array")

RegularExpressions
Be simple, but do not match the wrong thing.

Formatting:
* Tabs used instead of spaces.
* Long lines

DOM:
* Use of poor inferences; browser detection
* Use of non-standard approach or reliance on hacks
* Branching for multiple conditions when common approach works in more
browsers.
* If an approach requires several conditions to branch, look for a
different approach that works in all tested browsers.
* Traversing the dom on page load (slow) especially traversing DOM
using hand-rolled query selector.

Instead of traversing the DOM, use Event delegation.
Comments:

* Inaccurate statement in comment
* Comment doesn't match what code does
--
Garrett
comp.lang.javascript FAQ: http://jibbering.com/faq/

Erwin Moller

unread,
Dec 22, 2009, 5:11:48 AM12/22/09
to
Garrett Smith schreef:

> I'm putting together a couple of documents:
>
> 1) code guidelines
> 2) code review guidelines
>
> The goals are to help make for better code reviews here and to help
> debate on assessing javascript code quality.
>
> I'd like to start with my outline of code guidelines and get some
> feedback on it.
>

<snipped>

Hello Garrett,

Sounds very interesting.
I have read through it and I hope you will also give the reason for the
do's and don'ts.
Maybe with good examples and poor examples and some background information.

That would be a great document for starters and JavaScript programmers
with moderate experience.

There is so much (poor) advice on the net when it comes to JavaScript,
that is is often hard to find the right approach if you are not a
specialist (in which case you don't need to search the web).

Good luck!

Regards,
Erwin Moller


--
"There are two ways of constructing a software design: One way is to
make it so simple that there are obviously no deficiencies, and the
other way is to make it so complicated that there are no obvious
deficiencies. The first method is far more difficult."
-- C.A.R. Hoare

Dmitry A. Soshnikov

unread,
Dec 22, 2009, 5:55:31 AM12/22/09
to
On Dec 22, 2:52 am, Garrett Smith <dhtmlkitc...@gmail.com> wrote:

Good parts, thanks.

>
>   * inconsistent return types
> Methods should return one type; returning null instead of an Object
> may be a fair consideration.
>

Not necessarily. Method can be sort of factory, which returns
different type values. Or, e.g. "analysis returns" when check is
negative so simply exit from the function - there's no need to analyze
this code more; in this case nor value neither its type is so
essential (simple "return;" can be used without explicit value -
implicit undefined), but maybe "return null;" will be better. From the
other hand - why "return null" if the return statement at the end
returns e.g. number (will you use "return -1" then)?

// just exit, no need to analyze
// code bellow if first check is not pass
if (!someCheck)
return;

// other calculations

return 100;


> goog.isDef = function(val) {
>    return val !== undefined;};
>
> Instead, replace useless method with typeof check:
> if(typeof val === "undefined"){ }
>

From the speed point of view, calling function (establishing the new
context and so on) sure is less effective. From the abstraction point
of view, shorter wrapper can be better - with the same check inside -
everyone chooses. I use typeof val === "undefined", but not against
simple short wrappers.

/ds

John G Harris

unread,
Dec 22, 2009, 6:04:07 AM12/22/09
to
On Mon, 21 Dec 2009 at 15:52:55, in comp.lang.javascript, Garrett Smith
wrote:

<snip>


>Formatting:
> * Tabs used instead of spaces.

Spaces are preferred, I hope.


<snip>


>Comments:
>
> * Inaccurate statement in comment
> * Comment doesn't match what code does

Avoid too many comments. (Let the code speak for itself).

Remember to update comments when the code is changed.

John
--
John Harris

Asen Bozhilov

unread,
Dec 22, 2009, 6:24:32 AM12/22/09
to
Garrett Smith wrote:

>   * Boolean conversion of Host object (sometimes Error-prone)

//Boolean conversation host object in JScript
var xhr = new ActiveXObject('Microsoft.XMLHTTP');
window.alert(Object.prototype.hasOwnProperty.call(xhr, 'open')); //
true
try {
Boolean(xhr.open);
}catch(e)
{
window.alert(e instanceof TypeError); //true
window.alert(e); //Object doesn't support this property or method
}
window.alert(typeof xhr.open); //unknown

Dmitry A. Soshnikov

unread,
Dec 22, 2009, 6:48:09 AM12/22/09
to
On Dec 22, 2:52 am, Garrett Smith <dhtmlkitc...@gmail.com> wrote:

>
> Statements:
>   * Use of == where === should be used

> if(typeof val === "undefined"){ }
>

typeof returns always string, so there's no any difference using == or
=== in this case (algorithms are equivalent: word for word); == is
less on one symbol, you can use typeof val == 'undefined'.

/ds

Asen Bozhilov

unread,
Dec 22, 2009, 2:28:46 PM12/22/09
to
Dmitry A. Soshnikov wrote:

> > Statements:
> >   * Use of == where === should be used
> > if(typeof val === "undefined"){ }
>
> typeof returns always string, so there's no any difference using == or
> === in this case (algorithms are equivalent: word for word); == is
> less on one symbol, you can use typeof val == 'undefined'.

Yes, here you are absolutely right. But `==' can be harmful especially
when `EqualityExpression` and `RelationalExpression` ares from
different type, because one of them will be converted to primitive
value.

| 11.9.3 The Abstract Equality Comparison Algorithm

| 1. If Type(x) is different from Type(y), go to step 14.
| [...]
| 21. If Type(x) is Object and Type(y) is either String or Number,
| return the result of the comparison ToPrimitive(x) == y.

ToPrimitive for `object` call internal [[DefaultValue]] of passed
`object'. If `object' properties `toString' and `valueOf' is not a
objects [[DefaultValue]] throw TypeError.

e.g.

var o = {toString : null, valueOf : null};
try {
o == '';
}catch(e)
{
window.alert(e instanceof TypeError);
}

Dmitry A. Soshnikov

unread,
Dec 22, 2009, 4:16:47 PM12/22/09
to

Thanks, I know about that. But I mentioned about exactly typeof
operator and string 'undefined' (of whatevery) but not about o ==
'' ;) And from this point of view == would be enough; === in this case
is obsolete.

/ds

Asen Bozhilov

unread,
Dec 22, 2009, 5:20:11 PM12/22/09
to
Asen Bozhilov wrote:
> Garrett Smith wrote:
> >   * Boolean conversion of Host object (sometimes Error-prone)
>
> //Boolean conversation host object in JScript
> var xhr = new ActiveXObject('Microsoft.XMLHTTP');
> Boolean(xhr.open);

Garrett do you have any others example where Boolean conversion throw
Error?

In my example error will be throwing from internal [[Get]] method of
`object' referred from `xhr'.

var xhr = new ActiveXObject('Microsoft.XMLHTTP');

try {
var a = xhr.open;
}catch(e)
{


window.alert(e); //Object doesn't support this property or method
}

Here isn't the problem in type conversion. The problem is before that.
That example can show it own implementation of [[Get]] and [[Put]]
methods from that host object.

var xhr = new ActiveXObject('Microsoft.XMLHTTP');

try {
xhr.open = null;
}catch(e)
{
if (e instanceof ReferenceError)
{
window.alert('8.7.2 PutValue(V) throw ReferenceError');
}
window.alert(e); //TypeError
}

Can you show better example, because ECMA3 9.2 ToBoolean explicit
say:

| The operator ToBoolean converts its argument to a value of
| type Boolean according to the following table:
| [...]
| Object true

Abstract for me that mean:

function ToBoolean(value)
{
if (Type(value) === Object)
{
return true;
}
}

So at the moment i can't see where explicit or implicit conversion of
any object Native or Host can produce error.

Garrett Smith

unread,
Dec 22, 2009, 6:19:45 PM12/22/09
to
Asen Bozhilov wrote:
> Dmitry A. Soshnikov wrote:
>
>>> Statements:
>>> * Use of == where === should be used
>>> if(typeof val === "undefined"){ }
>> typeof returns always string, so there's no any difference using == or
>> === in this case (algorithms are equivalent: word for word); == is
>> less on one symbol, you can use typeof val == 'undefined'.
>
> Yes, here you are absolutely right. But `==' can be harmful especially
> when `EqualityExpression` and `RelationalExpression` ares from
> different type, because one of them will be converted to primitive
> value.
>

Yes, Dmitry is correct, you're both right. I wasn't explicit enough, or
used terminology that was open to interpretation.

Changed to:
* Use of == where strict equality is required
Where strict equality is required, the strict equality operator must be
used. The strict equality operator should always be used to compare
identity.

Example:-
// Do not use == to compare identity.
if (element == target) {
return true;
}


In the case of checking to see if a value can be null or undefined, I
don't have any problem with:-

if(v == null) {

}

Others do not using == to loose check. JSLint will error on that, I
believe.

[...]

Garrett Smith

unread,
Dec 22, 2009, 7:01:40 PM12/22/09
to
Asen Bozhilov wrote:
> Asen Bozhilov wrote:
>> Garrett Smith wrote:
>>> * Boolean conversion of Host object (sometimes Error-prone)
>> //Boolean conversation host object in JScript
>> var xhr = new ActiveXObject('Microsoft.XMLHTTP');
>> Boolean(xhr.open);
>
> Garrett do you have any others example where Boolean conversion throw
> Error?
>

No, you're right, I was mistaken. That should be replaced with something
appropriate.

> In my example error will be throwing from internal [[Get]] method of
> `object' referred from `xhr'.
>
> var xhr = new ActiveXObject('Microsoft.XMLHTTP');
> try {
> var a = xhr.open;
> }catch(e)
> {
> window.alert(e); //Object doesn't support this property or method
> }
>

> Here isn't the problem in type conversion. The problem is before that.
> That example can show it own implementation of [[Get]] and [[Put]]
> methods from that host object.
>

You're right about it not being ToBoolean. The error is from accessing
the property. I had believe the error was caused by type conversion.

Without doing anything with xhr.open method:-

javascript: new ActiveXObject('Microsoft.XMLHTTP').open;
Error: Object doesn't support this property or method.

Thanks for pointing that out.

| * Error-prone handling of Host objects.
| Potentially disconnected nodes behave differently
| javascript: void document.createElement("div").offsetParent;
| Unspecified Error in IE.
| Instead, use typeof to avoid undefined values or IE "unknown" types:
| var div = document.createElement("div");
| isOffsetParentSafe = !/^un/.test(typeof div.offsetParent);

Thomas 'PointedEars' Lahn

unread,
Dec 22, 2009, 7:11:02 PM12/22/09
to
Garrett Smith wrote:

> Changed to:
> * Use of == where strict equality is required
> Where strict equality is required, the strict equality operator must be
> used.

That goes without saying.

> The strict equality operator should always be used to compare
> identity.
>
> Example:-
> // Do not use == to compare identity.
> if (element == target) {
> return true;
> }

Define `identity'. It makes no difference whether `==' or `===' is used if
both values are object references (as in "objects have identity"). To be
exact, it makes no difference whether `==' or `===' is used if both values
are of the same internal type, e.g., Object. That is, it makes only a
little difference with regard to compatibility as `==' is slightly more
compatible than `==='.



> In the case of checking to see if a value can be null or undefined, I
> don't have any problem with:-
>
> if(v == null) {
>
> }

ACK. Then again, one seldom needs that because with a function one wants to
differentiate whether an argument was not passed, whereas the value of the
argument were `undefined', or whether `null' was passed. In all other cases
either host objects are involved and a `typeof' test is safer, or native
objects are involved and a type-converting test is more efficient.

> Others do not using == to loose check. [...]

Parse error.


PointedEars
--
Danny Goodman's books are out of date and teach practices that are
positively harmful for cross-browser scripting.
-- Richard Cornford, cljs, <cife6q$253$1$8300...@news.demon.co.uk> (2004)

RobG

unread,
Dec 22, 2009, 10:38:46 PM12/22/09
to
On Dec 22, 9:52 am, Garrett Smith <dhtmlkitc...@gmail.com> wrote:
> I'm putting together a couple of documents:
>
> 1) code guidelines
> 2) code review guidelines
>
> The goals are to help make for better code reviews here and to help
> debate on assessing javascript code quality.
>
> I'd like to start with my outline of code guidelines and get some
> feedback on it.
>
> Rich Internet Application Development Code Guildelines (Draft)
>
> Problems:
>
> Markup:
> * Invalid HTML
> * sending XHTML as text/html
> * xml prolog (cause problems in IE)
> * javascript: pseudo protocol
> * Not escaping ETAGO.
> Replace: "</" + "script>"
> with: "<\/script>";
> Replace: "</td>";
> with: "<\/td>";

I don't understand the issue here, is it specifically with the TD end
tag? Or is it more generally with end tags in HTML sent as an XHR
response?

A suitable alternative may be to omit the closing TD tag altogether
(valid in HTML 4.01 and draft HTML 5).

<URL: http://www.w3.org/TR/html5/syntax.html#syntax-tag-omission >

> CSS:
> * invalid css
> * classNames that do not have semantic meaning

While that comment is OK for class values used for CSS, it should be
noted that class names are not intended for CSS only.


[...]


> RegularExpressions
> Be simple, but do not match the wrong thing.

Not sure what that means.


--
Rob

Garrett Smith

unread,
Dec 23, 2009, 12:19:15 AM12/23/09
to
Thomas 'PointedEars' Lahn wrote:
> Garrett Smith wrote:
>
>> Changed to:
>> * Use of == where strict equality is required
>> Where strict equality is required, the strict equality operator must be
>> used.
>
> That goes without saying.
>

It is a true statement, but not obvious to all. The recent discussion on
Qooxdoo had an example of using == to compare two objects. I commented
that that comparison should use strict equality. That avoids cases
where, say, comparing a and b, a is null and b is empty string.

Same goes with unqualified assignment.

>> The strict equality operator should always be used to compare
>> identity.
>>
>> Example:-
>> // Do not use == to compare identity.
>> if (element == target) {
>> return true;
>> }
>
> Define `identity'.

The same unique object. As in, "if source is the target..."

if(source === target) {

}

and not:-

if(source == target) {

}

The strict equality tests leaves no ambiguity to the reader of the code
that the intent is to check identity. There is no room for considering
what happens when one operand is a different type.

It makes no difference whether `==' or `===' is used if
> both values are object references (as in "objects have identity"). To be
> exact, it makes no difference whether `==' or `===' is used if both values
> are of the same internal type, e.g., Object. That is, it makes only a
> little difference with regard to compatibility as `==' is slightly more
> compatible than `==='.
>

I think you meant "built-in" where you wrote "internal type". While it
is true that comparing two native ES objects using == does not result in
conversion, it still allows the possibility where when one side of the
operation is not an object, then conversion will happen. It may seem
unlikely to occur, but the added insurance of using === doesn't hurt. It
can actually result in nanosecond performance increase in IE.

For host object, == can be true while === is false.

javascript: alert( self === window );// false
javascript: alert( self == window ); // true

David Mark

unread,
Dec 23, 2009, 12:30:47 AM12/23/09
to
On Dec 23, 12:19 am, Garrett Smith <dhtmlkitc...@gmail.com> wrote:
> Thomas 'PointedEars' Lahn wrote:
> > Garrett Smith wrote:
>
> >> Changed to:
> >>   * Use of == where strict equality is required
> >> Where strict equality is required, the strict equality operator must be
> >> used.
>
> > That goes without saying.
>
> It is a true statement, but not obvious to all. The recent discussion on
> Qooxdoo had an example of using == to compare two objects. I commented
> that that comparison should use strict equality. That avoids cases
> where, say, comparing a and b, a is null and b is empty string.

Do you mean b is undefined?

null != ''

David Mark

unread,
Dec 23, 2009, 12:37:51 AM12/23/09
to
On Dec 22, 10:38 pm, RobG <rg...@iinet.net.au> wrote:
> On Dec 22, 9:52 am, Garrett Smith <dhtmlkitc...@gmail.com> wrote:
>
>
>
> > I'm putting together a couple of documents:
>
> > 1) code guidelines
> > 2) code review guidelines
>
> > The goals are to help make for better code reviews here and to help
> > debate on assessing javascript code quality.
>
> > I'd like to start with my outline of code guidelines and get some
> > feedback on it.
>
> > Rich Internet Application Development Code Guildelines (Draft)
>
> > Problems:
>
> > Markup:
> >   * Invalid HTML
> >   * sending XHTML as text/html
> >   * xml prolog (cause problems in IE)
> >   * javascript: pseudo protocol
> >   * Not escaping ETAGO.
> > Replace: "</" + "script>"
> > with:    "<\/script>";
> > Replace: "</td>";
> > with:    "<\/td>";
>
> I don't understand the issue here, is it specifically with the TD end
> tag? Or is it more generally with end tags in HTML sent as an XHR
> response?

No, it refers to markup in script (e.g. document.write calls).
Nothing to do with the tag type.

>
> A suitable alternative may be to omit the closing TD tag altogether
> (valid in HTML 4.01 and draft HTML 5).
>
> <URL:http://www.w3.org/TR/html5/syntax.html#syntax-tag-omission>
>
> > CSS:
> >   * invalid css
> >   * classNames that do not have semantic meaning
>
> While that comment is OK for class values used for CSS, it should be
> noted that class names are not intended for CSS only.

I try to avoid that.

>
> [...]
>
> > RegularExpressions
> >    Be simple, but do not match the wrong thing.
>
> Not sure what that means.

Seems overly simplified.

Garrett Smith

unread,
Dec 23, 2009, 2:12:58 AM12/23/09
to
RobG wrote:
> On Dec 22, 9:52 am, Garrett Smith <dhtmlkitc...@gmail.com> wrote:

[...]

> I don't understand the issue here, is it specifically with the TD end
> tag? Or is it more generally with end tags in HTML sent as an XHR
> response?
>

* Not escaping ETAGO, or using concatenation to escape ETAGO.
Inline script must not contain the character sequence "</"

http://www.w3.org/TR/WD-script-970314

When concatenating strings of HTML in an inline script, a backslash
should appear before the solidus symbol in the sequence "</", resulting
in "<\/", and not - "<" + "/" -.

> A suitable alternative may be to omit the closing TD tag altogether
> (valid in HTML 4.01 and draft HTML 5).
>
> <URL: http://www.w3.org/TR/html5/syntax.html#syntax-tag-omission >
>
>> CSS:
>> * invalid css
>> * classNames that do not have semantic meaning
>
> While that comment is OK for class values used for CSS, it should be
> noted that class names are not intended for CSS only.
>

True. Non-semantic class or ID lacks meaning (HTML and CSS). The same
applies to ID.

Instead, class and id should be meaningful, so the code is easier to
understand.

Bad:
.errorButton, #warningMessage

Good:

>
> [...]
>> RegularExpressions
>> Be simple, but do not match the wrong thing.
>
> Not sure what that means.

The context of a Regular Expression is is as important as what it can
match. A complex regular expression is harder to understand than a
simple one and so simple regular expressions are preferred. It is OK the
expression can match the wrong thing, just so long as the context in
which it is used precludes or handles that.

// Wrong: Matches 137, 138...
ARROW_KEY_EXP : /37|38|39|40/;

// Right: matches only arrow keys.
ARROW_KEY_EXP : /^(?:37|38|39|40)$/;

// Simple: Can match the wrong thing, but that can be handled.
var iso8601Exp = /^\s*([\d]{4})-(\d\d)-(\d\d)\s*$/;

Trying to match leap years would be excessively complex.
Instead, the date validation can be addressed where the expression is used.

Garrett Smith

unread,
Dec 23, 2009, 2:14:34 AM12/23/09
to

Yes, of course!

> null != ''

Of course, I know that. Thanks for pointing it out though.

Garrett Smith

unread,
Dec 23, 2009, 2:15:40 AM12/23/09
to
Garrett Smith wrote:
> Thomas 'PointedEars' Lahn wrote:
>> Garrett Smith wrote:
>>
>>> Changed to:
>>> * Use of == where strict equality is required
>>> Where strict equality is required, the strict equality operator must be
>>> used.
>>
>> That goes without saying.
>>
>
> It is a true statement, but not obvious to all. The recent discussion on
> Qooxdoo had an example of using == to compare two objects. I commented
> that that comparison should use strict equality. That avoids cases
> where, say, comparing a and b, a is null and b is empty string.

Correction:
where, say, comparing - a - is null and - b - is undefined.

Asen Bozhilov

unread,
Dec 23, 2009, 3:32:32 AM12/23/09
to
Garrett Smith wrote:

> RegularExpressions
> Be simple, but do not match the wrong thing.

I ever wondering about using RegExp for type checking.

/^\s*\bfunction\b/.test("" + f);

That will be check implementation depended string returned from
f.toString(); for as function, and that checking can be falsish.

e.g.

var o = {
toString : function()
{
return 'function function';
}
};
window.alert(/^\s*\bfunction\b/.test("" + o)); //true

Dmitry A. Soshnikov

unread,
Dec 23, 2009, 5:03:08 AM12/23/09
to
On Dec 23, 2:19 am, Garrett Smith <dhtmlkitc...@gmail.com> wrote:

[snip]

>
> Yes, Dmitry is correct, you're both right. I wasn't explicit enough, or
> used terminology that was open to interpretation.
>
> Changed to:
> * Use of == where strict equality is required
> Where strict equality is required, the strict equality operator must be
> used. The strict equality operator should always be used to compare
> identity.
>

The previous description (with ===) was quite understandable too, and
goes without saying, I meant not that. I mean that there's no any
reason to use === with `typeof' operator. So you can easily always
use:

if (typeof blaBla == 'undefined') {
...
}

'cause, repeat, algorithms are equivalent in this case as `typeof'
always returns value of string type.

/ds

Dr J R Stockton

unread,
Dec 23, 2009, 2:39:41 PM12/23/09
to
In comp.lang.javascript message <+KuB1xEn...@J.A830F0FF37FB96852AD0
8924D9443D28E23ED5CD>, Tue, 22 Dec 2009 11:04:07, John G Harris
<jo...@nospam.demon.co.uk> posted:

>On Mon, 21 Dec 2009 at 15:52:55, in comp.lang.javascript, Garrett Smith
>wrote:
>
> <snip>
>>Formatting:
>> * Tabs used instead of spaces.
>
>Spaces are preferred, I hope.

Some like larger indents. And a good viewing system can be set to make
a tab equivalent to two or three spaces. On the Web, however, tabs will
normally be worth up to 8 spaces, and should not be used as the indent
unit since most readers will find that too big.

AFAICS, however, tabs are fine for comment and in code strings and in
simple tables.

The primary objection is not to tabs as such, but to an over-wide indent
unit however produced.

AFAIK, in browser output, it is safe to assume tab stops at 8n+1; it may
not be so if the output goes, or is taken, elsewhere.

It should not be at all difficult to write script that will take tabbed
textarea content and replace tabs by appropriate spaces, including tab
stops at 2n+1 in leading whitespace, otherwise 8n+1. That should slim
the broader authors reasonably well. The FAQ site could, on another
page, offer such routines.

On long lines : while it is nice if everything fits in 72 characters,
that is not of prime importance. What matters is that the sending agent
must not machine-wrap lines of code (as it rightly will for text). A
well-designed receiving agent (such as yours) should not impose a fixed
right margin, and material that really needs longer lines should be sent
with those longer lines.

Desperate readers with primitive newsreaders should always be able to
save the article and read it a la Notepad.

--
(c) John Stockton, nr London 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.

Dr J R Stockton

unread,
Dec 23, 2009, 3:33:10 PM12/23/09
to
In comp.lang.javascript message <hgp1oo$vee$1...@news.eternal-
september.org>, Mon, 21 Dec 2009 15:52:55, Garrett Smith
<dhtmlk...@gmail.com> posted:

>Rich Internet Application Development Code Guildelines (Draft)

Remember the spelling/grammar checker.


> * non-localized strings

You should mean non-internationalised strings, since that is a list of
bad things.

Generally, one does better to list the good things.


> * inconsistent return types
>Methods should return one type; returning null instead of an Object
>may be a fair consideration.

Where successful operation of a routine cannot return anything
resembling false, ISTM reasonable and useful to return something
resembling false if the routine has failed to do what was wanted.


>Strategies:
> * Modifying built-in or Host object in ways that are either error
>prone or confusing (LOD).

Include : using without explanation jargon or any other than well-known
acronyms & abbreviations


>Strings:
> * use of concatenation to repeatedly (repeatedly create and
>discard temporary strings)
>Instead use String.prototype.concat(a, b, c) or htmlBuf.push(a, b, c);

Remember that the chief use of JavaScript by the untended FAQ readership
is to produce smallish pieces of code without much looping, running in a
Web browser as a result of a user action. There is no point at all in
telling a general FAQ reader that the less machine-efficient methods are
wrong, if they work perfectly well and the code will complete within 100
ms.

Writing the fastest code in a nice intellectual exercise for consenting
participants, but it should not be imposed overall. The best code is
easily-maintainable code, which generally means using a form of code
which will be readily understandable to the author in three months time.


>RegularExpressions
> Be simple, but do not match the wrong thing.

Generally - test not only that it works when it should, but also that it
does not work when it should not.

Include - don't repeat code where it can reasonably be avoided. Use
temporary variables, or functions or methods, for this.

--
(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 "-- " (RFCs 5536/7)
Do not Mail News to me. Before a reply, quote with ">" or "> " (RFCs 5536/7)

Dr J R Stockton

unread,
Dec 24, 2009, 4:42:07 PM12/24/09
to
In comp.lang.javascript message <hgsftu$dnu$1...@news.eternal-
september.org>, Tue, 22 Dec 2009 23:12:58, Garrett Smith
<dhtmlk...@gmail.com> posted:

{with RegExps]


>Trying to match leap years would be excessively complex.
>Instead, the date validation can be addressed where the expression is used.

Well, in the context I agree. But, for the festive season, the
following code alerts 7777 only (that was added to show that the loop
runs); the middle line does with a reasonably simple RegExp tell whether
Y is leap.

for (Y=0 ; Y<11111 ; Y++) if (
/([^5AF]0|[48CG])$/i.test((Y+400).toString(20))
!= !!(2-new Date(Y+400, 1, 29).getMonth() ) || Y == 7777 ) alert(Y)

The first 400 saves worrying about 1-digit years; the second compensates
and saves worrying about years before 100.

Tested only in FF 3.0.15.

--
(c) John Stockton, nr London, UK. ?@merlyn.demon.co.uk Turnpike v6.05.
Web <URL:http://www.merlyn.demon.co.uk/> - w. FAQish topics, links, acronyms
PAS EXE etc : <URL:http://www.merlyn.demon.co.uk/programs/> - see 00index.htm
Dates - miscdate.htm estrdate.htm js-dates.htm pas-time.htm critdate.htm etc.

David Mark

unread,
Dec 24, 2009, 7:08:38 PM12/24/09
to
On Dec 23, 3:33 pm, Dr J R Stockton <reply0...@merlyn.demon.co.uk>
wrote:
> In comp.lang.javascript message <hgp1oo$ve...@news.eternal-

> september.org>, Mon, 21 Dec 2009 15:52:55, Garrett Smith
> <dhtmlkitc...@gmail.com> posted:

>
> >Rich Internet Application Development Code Guildelines (Draft)
>
> Remember the spelling/grammar checker.
>
> > * non-localized strings
>
> You should mean non-internationalised strings, since that is a list of
> bad things.
>
> Generally, one does better to list the good things.
>
> > * inconsistent return types
> >Methods should return one type; returning null instead of an Object
> >may be a fair consideration.
>
> Where successful operation of a routine cannot return anything
> resembling false, ISTM reasonable and useful to return something
> resembling false if the routine has failed to do what was wanted.
>

That's an over-generalization. Functions that return nothing result
in the undefined value. That shouldn't mean they failed. It really
depends on the function, but there is no general reason to return a
"truthy" value.

> >Strategies:
> > * Modifying built-in or Host object in ways that are either error
> >prone or confusing (LOD).
>
> Include : using without explanation jargon or any other than well-known
> acronyms & abbreviations

typeof x == 'unknown'; // ActiveX (is that okay?)
(x); // Boom

>
> >Strings:
> > * use of concatenation to repeatedly (repeatedly create and
> >discard temporary strings)
> >Instead use String.prototype.concat(a, b, c) or htmlBuf.push(a, b, c);
>
> Remember that the chief use of JavaScript by the untended FAQ readership
> is to produce smallish pieces of code without much looping, running in a
> Web browser as a result of a user action.

"...as a result of a user action" is the operative phrase. Such
results _need_ to be as fast as possible. If you've ever typed into
an "autocomplete" widget, you know what I'm talking about.

> There is no point at all in
> telling a general FAQ reader that the less machine-efficient methods are
> wrong, if they work perfectly well and the code will complete within 100
> ms.

Huh? Repetitive string concatenation is a performance killer
(particularly in IE).

>
> Writing the fastest code in a nice intellectual exercise for consenting
> participants, but it should not be imposed overall.

I don't see what that has to do with excessive concatenation.

> The best code is
> easily-maintainable code, which generally means using a form of code
> which will be readily understandable to the author in three months time.

Pushing strings to an array and then joining (instead of
concatenating) is not going throw anyone (at least not anyone who
should be programming JS).

>
> >RegularExpressions
> >  Be simple, but do not match the wrong thing.
>
> Generally - test not only that it works when it should, but also that it
> does not work when it should not.

Seems sensible.

>
> Include - don't repeat code where it can reasonably be avoided.

Good.

> Use
> temporary variables, or functions or methods, for this.

Temporary variables? And it's not exactly clear what "this" is. :)

Garrett Smith

unread,
Dec 25, 2009, 2:01:09 AM12/25/09
to
Asen Bozhilov wrote:
> Garrett Smith wrote:
>
>> RegularExpressions
>> Be simple, but do not match the wrong thing.
>
> I ever wondering about using RegExp for type checking.
>
> /^\s*\bfunction\b/.test("" + f);
>
RegExp.test converts the argument to a string, so could be written as:-

/^\s*\bfunction\b/.test(f);

Type checking clutters the code up.

Type checking properties of Host object has been known to cause errors.
Safari 2 blows up when accessing a property off a NodeList.

The typeof operator can hide errors in IE, though, as discussed recently.
Example:-
javascript: alert(typeof document.styleSheets[-1] );

typeof hides error.

There should be a list of things that blow up in IE.

> That will be check implementation depended string returned from
> f.toString(); for as function, and that checking can be falsish.
>

f.toString() would resolve a toString property on the function before
calling it.

A function's toString property could be an own property. Otherwise, it
would be found in Function.prototype. The implementation-dependent
representation is required to be a FunctionDeclaration. In practice,
most implementations violate that as:-

(function(){}).toString();

The results is a string that is not a FunctionDeclaration (looks like a
FunctionDeclaration). The specification should change and I have
proposed this change to the ECMAScript committee. My proposal was to
change where it says "FunctionDeclaration" to "Function Definition".
This would legalize existing implementations' returning a string
representing a FunctionExpression.

Proposed:-
| 15.3.4.2 Function.prototype.toString ( )
|
| An implementation-dependent representation of the
| function is returned. This representation has the
| syntax of a Function Definition. Note in particular
| that the use and placement of white space, line
| terminators, and semicolons within the representation
| string is implementation-dependent.


https://mail.mozilla.org/pipermail/es-discuss/2009-September/009816.html

> e.g.
>
> var o = {
> toString : function()
> {
> return 'function function';
> }
> };
> window.alert(/^\s*\bfunction\b/.test("" + o)); //true
>

That is a different situation. Here we have an object that is not a
function, but has a toString that could result in a false positive.

new Object("Conjunction Junction, what's your function?");

Asen Bozhilov

unread,
Dec 25, 2009, 6:47:47 AM12/25/09
to
Garrett Smith wrote:
> Asen Bozhilov wrote:
> > Garrett Smith wrote:

> > /^\s*\bfunction\b/.test("" + f);
>
> RegExp.test converts the argument to a string, so could be written as:-
>
> /^\s*\bfunction\b/.test(f);

Yes, but do you can to explain next lines in IE:

var xhr = new ActiveXObject('Microsoft.XMLHTTP');
try {

String(xhr);


}catch(e) {
window.alert(e instanceof TypeError); //true
}

window.alert(('foo' + xhr).length); //3
window.alert(typeof ('foo' + xhr)); //string
window.alert(typeof (xhr + 'foo')); //undefined

| 15.5.1.1 String
| Returns a string value (not a String object)
| computed by ToString(value).

ToString for Object call ToPrimitive with hint `string`. ToPrimitve
call internal [[DefaultValue]] method of that Object. [[DefaultValue]]
throw TypeError if Object properties `toString' and `valueOf' is not a
objects.

| 11.6.1 The Addition operator ( + )
| The production AdditiveExpression :
| AdditiveExpression + MultiplicativeExpression
| is evaluated as follows:
| 1. Evaluate AdditiveExpression.
| 2. Call GetValue(Result(1)).
| 3. Evaluate MultiplicativeExpression.
| 4. Call GetValue(Result(3)).
| 5. Call ToPrimitive(Result(2)).
| 6. Call ToPrimitive(Result(4)).

Lets modified my example to use native object instead of host object:

var o = {toString : null, valueOf : null};
try {

String(o);


}catch(e) {
window.alert(e instanceof TypeError); //true
}

window.alert(('foo' + o).length); //3
window.alert(typeof ('foo' + o)); //string
window.alert(typeof (10 + o)); //number
window.alert(typeof (o + 'foo')); //object
window.alert(typeof (o + 10)); //object


window.alert(typeof (o + 'foo')); //object

Here i expected 'string' from 11.6.1 step 7.
| If Type(Result(5)) is String or Type(Result(6)) is String,
| go to step 12. (Note that this step differs from step 3 in
| the comparison algorithm for the relational operators,
| by using or instead of and.)


From what that i can see JScript use much complex algorithm in `The
Addition operator ( + )` and definitely they don't follow
documentation steps in `11.6.1 The Addition operator ( + )`. Can
anybody explain used algorithm of JScript?


Thomas 'PointedEars' Lahn

unread,
Dec 25, 2009, 12:48:08 PM12/25/09
to
Garrett Smith wrote:

> Thomas 'PointedEars' Lahn wrote:
>> Garrett Smith wrote:
>>> Changed to:
>>> * Use of == where strict equality is required
>>> Where strict equality is required, the strict equality operator must be
>>> used.
>>
>> That goes without saying.
>
> It is a true statement, but not obvious to all.

A spoon must be used where a spoon is required. How stupid does one have to
be not to recognize the inherent veracity of such statements?

Thomas 'PointedEars' Lahn

unread,
Dec 25, 2009, 6:19:36 PM12/25/09
to
David Mark wrote:

> On Dec 22, 10:38 pm, RobG <rg...@iinet.net.au> wrote:
>> On Dec 22, 9:52 am, Garrett Smith <dhtmlkitc...@gmail.com> wrote:

>> > * Not escaping ETAGO.

For better understanding, the exact term "ETAGO delimiter" should be used.

>> > Replace: "</" + "script>"
>> > with: "<\/script>";
>> > Replace: "</td>";
>> > with: "<\/td>";
>>
>> I don't understand the issue here, is it specifically with the TD end
>> tag? Or is it more generally with end tags in HTML sent as an XHR
>> response?
>
> No, it refers to markup in script (e.g. document.write calls).

ACK

> Nothing to do with the tag type.

The *what*? I thought this was comp.lang.javascript, not
alt.scriptkiddie.misc.


PointedEars
--
Prototype.js was written by people who don't know javascript for people
who don't know javascript. People who don't know javascript are not
the best source of advice on designing systems that use javascript.
-- Richard Cornford, cljs, <f806at$ail$1$8300...@news.demon.co.uk>

Thomas 'PointedEars' Lahn

unread,
Dec 25, 2009, 6:32:05 PM12/25/09
to
Garrett Smith wrote:

> RobG wrote:
>> I don't understand the issue here, is it specifically with the TD end
>> tag? Or is it more generally with end tags in HTML sent as an XHR
>> response?
>
> * Not escaping ETAGO, or using concatenation to escape ETAGO.
> Inline script must not contain the character sequence "</"
>
> http://www.w3.org/TR/WD-script-970314

There really is no reason here to go at lengths citing hopelessly outdated
material:

<http://www.w3.org/TR/html4/appendix/notes.html#notes-specifying-data>

> When concatenating strings of HTML in an inline script, a backslash
> should appear before the solidus symbol in the sequence "</", resulting
> in "<\/", and not - "<" + "/" -.

Do not confuse the solidus character (U+2044) with that of the US-ASCII-
compatible forward slash (U+002F), though.

>> A suitable alternative may be to omit the closing TD tag altogether
>> (valid in HTML 4.01 and draft HTML 5).

Wrong. It is Valid in HTML 4.01 Transitional only. As for the "HTML 5"
reference: When will you ever learn? And it certainly would not apply to
the "XHTML variant" of "HTML 5", whatever that is supposed to become some
day.



>>> CSS:
>>> * invalid css
>>> * classNames that do not have semantic meaning
>>
>> While that comment is OK for class values used for CSS, it should be
>> noted that class names are not intended for CSS only.
>
> True. Non-semantic class or ID lacks meaning (HTML and CSS). The same
> applies to ID.
>
> Instead, class and id should be meaningful, so the code is easier to
> understand.

Indubitably.

> Bad:
> .errorButton, #warningMessage
>
> Good:

IBTD.


PointedEars
--
var bugRiddenCrashPronePieceOfJunk = (
navigator.userAgent.indexOf('MSIE 5') != -1
&& navigator.userAgent.indexOf('Mac') != -1
) // Plone, register_function.js:16

Garrett Smith

unread,
Dec 25, 2009, 9:20:07 PM12/25/09
to
Thomas 'PointedEars' Lahn wrote:
> Garrett Smith wrote:
>
[...]

>> Instead, class and id should be meaningful, so the code is easier to
>> understand.
>
> Indubitably.
>
>> Bad:
>> .errorButton, #warningMessage
>>
>> Good:
>
> IBTD.
>

Good catch.

I put the "good" line in after "bad". Those are good examples.

I have the text in the draft:

Selectors such as .redButton, #ItalicStatement are meaningless.
Instead, use class and id that represent an object or state.
Example:

.errorButton, #warningMessage, .active-panel

This makes the code is easier to understand and doesn't
become meaningless when the styles change.

I am still replying to Stockton's comments on this, and it is a Holiday
here, so spending time with people now.

Garrett Smith

unread,
Dec 25, 2009, 9:47:53 PM12/25/09
to
Thomas 'PointedEars' Lahn wrote:
> Garrett Smith wrote:
>
>> Thomas 'PointedEars' Lahn wrote:
>>> Garrett Smith wrote:
>>>> Changed to:
>>>> * Use of == where strict equality is required
>>>> Where strict equality is required, the strict equality operator must be
>>>> used.
>>> That goes without saying.
>> It is a true statement, but not obvious to all.
>
> A spoon must be used where a spoon is required. How stupid does one have to
> be not to recognize the inherent veracity of such statements?
>

Not everyone knows the difference.

I have see a lot of code that uses == where === should have been used to
avoid the possibility of type conversion. When I see it, I point it out.

The mistake happens out of carelessness and inexperience.

I thought it would be useful to include this in the checklist, so that a
developer preparing the code for review could consider that.

Garrett Smith

unread,
Dec 26, 2009, 5:47:43 PM12/26/09
to
Dr J R Stockton wrote:
> In comp.lang.javascript message <hgp1oo$vee$1...@news.eternal-
> september.org>, Mon, 21 Dec 2009 15:52:55, Garrett Smith
> <dhtmlk...@gmail.com> posted:
>
>> Rich Internet Application Development Code Guildelines (Draft)
>
> Remember the spelling/grammar checker.
>

Code Guidelines for Rich Internet Application Development

What do you think?

>
>> * non-localized strings
>
> You should mean non-internationalised strings, since that is a list of
> bad things.
>

I meant non-localized. For example, a problematic script that has:
showMessage("please enter your last name");

> Generally, one does better to list the good things.
>

The document is intended to be used primarily as a checklist for code
review preparation. Code must meet acceptibility criterion before going
into production, so that it can be determined if it is good or not.

It is foolish and omnipresent practice to ship messes to production.
This happens for many reasons, ignorance being the largest.

One such form of ignorance is the lack of criteria or standard by which
to assess code quality. This ignorance can be eliminated or at least
alleviated by providing a list of guidelines that defines code quality.

The code guidelines has been changed so that it is in the positive
sense, where appropriate, and negative sense, where appropriate. For
example:-

Markup:
* Use valid html.
* Use standards mode, with DOCTYPE first (no comment, xml prolog).
* Send html documents as text/html.
* Escape ETAGO with backwards solidus (backslash).
http://www.cs.tut.fi/~jkorpela/www/revsol.html
* Do not use javascript: pseudo protocol.

Sound better?

It may be worth considering assigning priority labels to certain things.
For example: "Use valid HTML" an "Use standards mode" would be priority
1 guidelines, while "Use efficient string concatenation techniques"
might be a Priority 2, while

>
>> * inconsistent return types
>> Methods should return one type; returning null instead of an Object
>> may be a fair consideration.
>
> Where successful operation of a routine cannot return anything
> resembling false, ISTM reasonable and useful to return something
> resembling false if the routine has failed to do what was wanted.
>

Functions that return multiple type provide more variance to the caller.

Sometimes this happens on accident, where the function was
intended to return one type, but can return a value of a different type.

Functions that return only one value type (including undefined) do not
burden the caller with having to check the return type.

It is something to look for in code where the function may, for example,
return a number in one case and a string in another case.

Functions that return multiple type have their place. A method might
return an object, but return null if the operation failed. So it is not
a rule, but something to consider when looking the code.

>
>> Strategies:
>> * Modifying built-in or Host object in ways that are either error
>> prone or confusing (LOD).
>
> Include : using without explanation jargon or any other than well-known
> acronyms & abbreviations
>

"Don't modify objects you don't own".

A piece of code that modifies objects it does not own creates a coupling
with those modifications and anything using that piece of code.

This coupling creates a dependency of those modifications to all the
dependencies of the code that exists in that codebase. Dependency of
those modifications is maximized to every piece of code that uses the
module that has modified them. Sometimes dependencies may even collide.
For example, one piece of code may create Element.prototype.hide, and
another piece of code may create a different Element.prototype.hide.

Instead, a separate interface should be created. The interface can be as
simple as a function. For example: hideElement( el ).

A fair exception to that rule would be for adding or fixing properties
that are either not yet implemented, or do not function as specified in
the standard.

if(!String.prototype.trim) {
// Patch for missing ES5 method.
}

An additional problem occurs modifying Host objects or Host objects'
constructors' prototypes. The outcome of this isn't specified and won't
work consistently cross-browser. The interface-based API design of the
w3c DOM allows for sub-interface to provide a more specific
implementation that shadows the user-defined method of the same name
further up in the prototype chain.

The w3c DOM does not prevent implementations from creating their own
interfaces. Quite often implementations do create interfaces that are
interwoven through the interface hierarchy. Such interfaces may or may
not be accessible to code.

>
>> Strings:
>> * use of concatenation to repeatedly (repeatedly create and
>> discard temporary strings)
>> Instead use String.prototype.concat(a, b, c) or htmlBuf.push(a, b, c);
>
> Remember that the chief use of JavaScript by the untended FAQ readership
> is to produce smallish pieces of code without much looping, running in a
> Web browser as a result of a user action. There is no point at all in
> telling a general FAQ reader that the less machine-efficient methods are
> wrong, if they work perfectly well and the code will complete within 100
> ms.
>

The code guidelines doc will help identify principles that make code
good and problems in code.

A motivation for this is to help facilitate better code reviews.

Some people would define good code as code that works, but that is a
very low standard.

Many recent posts on this list are a large dump of unformatted code,
followed by, and interspersed with, non-technical remarks and insults
directed towards the code author. Usually missing all or most of the
actual bugs in the process.

There is no document that defines *good* set of principles by which to
judge code.

I recently saw this entry on stack overflow:-
http://stackoverflow.com/questions/87896/code-reviews-on-the-web-for-php-and-javascript-code

| What are the best places for freelancers or small companies to get
| code reviewed for PHP and JavaScript? Forums are an option, but are
| there any sites dedicated specifically to code reviews?

There is a lot of advice out there already. Some online documents that I
have read web advocate principles without justification, make false
statements, and show bias by advocating a particular library.

> Writing the fastest code in a nice intellectual exercise for consenting
> participants, but it should not be imposed overall. The best code is
> easily-maintainable code, which generally means using a form of code
> which will be readily understandable to the author in three months time.
>

Code optimizations don't always reduce clarity. The best solutions are
simple and efficient. String.prototype.concat is simple and easy way to
avoid IE's slow string handling.

>
>> RegularExpressions
>> Be simple, but do not match the wrong thing.
>
> Generally - test not only that it works when it should, but also that it
> does not work when it should not.

That applies to functions, too.

> Include - don't repeat code where it can reasonably be avoided. Use
> temporary variables, or functions or methods, for this.
>

That's the basis for one of the DRY principle.

SOLID principles can also apply to js application architecture. SRP
applies to functions. LSP seems less closely related to js programming
where user-defined inheritance structures do not exist, though YUI panel
is an example of LSP violation.

SRP The Single Responsibility Principle
A class should have one, and only one, reason to change.
OCP The Open Closed Principle
You should be able to extend a classes behavior, without modifying it.
LSP The Liskov Substitution Principle
Derived classes must be substitutable for their base classes.
DIP The Dependency Inversion Principle
Depend on abstractions, not on concretions.
ISP The Interface Segregation Principle
Make fine grained interfaces that are client specific.

Eric Bednarz

unread,
Dec 26, 2009, 6:14:46 PM12/26/09
to
Garrett Smith <dhtmlk...@gmail.com> writes:

> * Use valid html.

If that really was a valid requirement for web authoring, it wouldn’t be
joined by deep confusion about very basic and simple issues in almost
all cases.

> * Use standards mode, with DOCTYPE first (no comment, xml prolog).

Well, that didn’t take long. The document type declaration *is part of
the prolog*, in both XML and SGML productions.

Garrett Smith

unread,
Dec 26, 2009, 6:24:37 PM12/26/09
to
Garrett Smith wrote:
> Dr J R Stockton wrote:
>> In comp.lang.javascript message <hgp1oo$vee$1...@news.eternal-
>> september.org>, Mon, 21 Dec 2009 15:52:55, Garrett Smith
>> <dhtmlk...@gmail.com> posted:
>>
>>> Rich Internet Application Development Code Guildelines (Draft)
>>

[...]

> * Escape ETAGO with backwards solidus (backslash).

Changed in draft to "Escape ETAGO delimiter".
[...]


>
> An additional problem occurs modifying Host objects or Host objects'
> constructors' prototypes.

Should be "DOM objects' constructors' prototypes", to reflect ES5 change
to the definition of Host object, and the fact that a browser may
implement DOM object as Native object.

[...]


>
>> Include - don't repeat code where it can reasonably be avoided. Use
>> temporary variables, or functions or methods, for this.
>>
> That's the basis for one of the DRY principle.
>

correction: "for the DRY principle", not "for one of the DRY principle".

David Mark

unread,
Dec 26, 2009, 6:24:52 PM12/26/09
to
On Dec 25, 6:19 pm, Thomas 'PointedEars' Lahn <PointedE...@web.de>
wrote:

> David Mark wrote:
> > On Dec 22, 10:38 pm, RobG <rg...@iinet.net.au> wrote:
> >> On Dec 22, 9:52 am, Garrett Smith <dhtmlkitc...@gmail.com> wrote:
> >> > * Not escaping ETAGO.
>
> For better understanding, the exact term "ETAGO delimiter" should be used.
>
> >> > Replace: "</" + "script>"
> >> > with:    "<\/script>";
> >> > Replace: "</td>";
> >> > with:    "<\/td>";
>
> >> I don't understand the issue here, is it specifically with the TD end
> >> tag? Or is it more generally with end tags in HTML sent as an XHR
> >> response?
>
> > No, it refers to markup in script (e.g. document.write calls).
>
> ACK
>
> > Nothing to do with the tag type.
>
> The *what*?  I thought this was comp.lang.javascript, not
> alt.scriptkiddie.misc.

The type of tag serialized in the string (e.g. TD vs. SCRIPT). Are
you proposing to refer to these as *elements*? I think not as we are
talking about just one (ending) tag (not both).

Dr J R Stockton

unread,
Dec 26, 2009, 5:14:53 PM12/26/09
to
In comp.lang.javascript message <7895e8b5-1f6f-4a3c-9e09-11d5379a3973@n1
3g2000vbe.googlegroups.com>, Thu, 24 Dec 2009 16:08:38, David Mark
<dmark....@gmail.com> posted:

>On Dec 23, 3:33�pm, Dr J R Stockton <reply0...@merlyn.demon.co.uk>
>wrote:
>> In comp.lang.javascript message <hgp1oo$ve...@news.eternal-
>> september.org>, Mon, 21 Dec 2009 15:52:55, Garrett Smith
>> <dhtmlkitc...@gmail.com> posted:

>> > * inconsistent return types


>> >Methods should return one type; returning null instead of an Object
>> >may be a fair consideration.
>>
>> Where successful operation of a routine cannot return anything
>> resembling false, ISTM reasonable and useful to return something
>> resembling false if the routine has failed to do what was wanted.
>>
>
>That's an over-generalization. Functions that return nothing result
>in the undefined value. That shouldn't mean they failed. It really
>depends on the function, but there is no general reason to return a
>"truthy" value.

"A implies B" does not imply "not A implies not B", although the
converse seems to be taught in American schools.

If the "main results" of a function are obtained other than through the
returned value of the function, then one can still return false if it
fails, but one should then return true if it succeeds.

But clearly I had in mind a function which returns its main results.

>> >Strategies:
>> > * Modifying built-in or Host object in ways that are either error
>> >prone or confusing (LOD).
>>
>> Include : using without explanation jargon or any other than well-known
>> acronyms & abbreviations
>
>typeof x == 'unknown'; // ActiveX (is that okay?)
>(x); // Boom

A pointless remark.

>> >Strings:
>> > * use of concatenation to repeatedly (repeatedly create and
>> >discard temporary strings)
>> >Instead use String.prototype.concat(a, b, c) or htmlBuf.push(a, b, c);
>>
>> Remember that the chief use of JavaScript by the untended FAQ readership
>> is to produce smallish pieces of code without much looping, running in a
>> Web browser as a result of a user action.
>
>"...as a result of a user action" is the operative phrase. Such
>results _need_ to be as fast as possible. If you've ever typed into
>an "autocomplete" widget, you know what I'm talking about.

Utter nonsense. If the calculation and display take less than about 100
ms from user initiation, there is no benefit in speeding them up.

FF 3.0.15, XPsp3, P43GHz,
<URL:http://www.merlyn.demon.co.uk/js-misc0.HTM#MLS> :
100,000 sequential concatenations of a 9-character string, by Turtle,
takes under 0.06 seconds. That, for a member of the intended FAQ
readership, is rarely of any importance.

>> There is no point at all in
>> telling a general FAQ reader that the less machine-efficient methods are
>> wrong, if they work perfectly well and the code will complete within 100
>> ms.
>
>Huh? Repetitive string concatenation is a performance killer
>(particularly in IE).

Perhaps you should test that assertion. Possibly you are an aged
person, raised on JavaScript in early browsers running on 486/33 CPUs or
similar, when code ran a hundred or more times slower than it does
today. Nevertheless, the real point which you show no signs of having
grasped is that, for most of the work of those who the FAQ is intended
to help the difference between the various methods will be at most a few
milliseconds, which DOES NOT MATTER.

If a string is short enough to be displayed of an ordinary Web page of
reasonable size, then any method of joining its natural parts will be
fast enough.

>> Writing the fastest code in a nice intellectual exercise for consenting
>> participants, but it should not be imposed overall.
>
>I don't see what that has to do with excessive concatenation.

Your problem.


>> Include - don't repeat code where it can reasonably be avoided.
>
>Good.
>
>>�Use
>> temporary variables, or functions or methods, for this.
>

>Temporary variables? And it's not exactly clear what "this" is. :)

Your problem. It is repeating code where it can reasonably be avoided.

Examples :

Don't repeat getElementById on the same element unnecessarily; save the
reference in a temporary variable, for readability.

Don't multiply repeat, with different variables, such as M D h m s,
if (M<10) M = "0" + M
but use a function such as
function LZ(n) { return (n!=null&&n<10&&n>=0?"0":"") + n }
or function LZ(n) { return (n<10?"0":"") + n }

--
(c) John Stockton, nr London, UK. ?@merlyn.demon.co.uk Turnpike v6.05 MIME.
Web <URL:http://www.merlyn.demon.co.uk/> - FAQqish topics, acronyms & links;
Astro stuff via astron-1.htm, gravity0.htm ; quotings.htm, pascal.htm, etc.
No Encoding. Quotes before replies. Snip well. Write clearly. Don't Mail News.

Garrett Smith

unread,
Dec 26, 2009, 6:50:59 PM12/26/09
to
Maybe so, but for HTML, no comments and no prolog will trigger quirks
mode in IE. They should both be avoided for this reason.

Garrett Smith

unread,
Dec 26, 2009, 6:57:11 PM12/26/09
to
Garrett Smith wrote:
> Eric Bednarz wrote:
>> Garrett Smith <dhtmlk...@gmail.com> writes:

[...]

>> Well, that didn’t take long. The document type declaration *is part of
>> the prolog*, in both XML and SGML productions.
> Maybe so, but for HTML, no comments and no prolog will trigger quirks
> mode in IE. They should both be avoided for this reason.

Correction:
"comments and/or prolog will trigger quirks mode in IE."

Dmitry A. Soshnikov

unread,
Dec 27, 2009, 5:26:39 AM12/27/09
to
On Dec 27, 1:47 am, Garrett Smith <dhtmlkitc...@gmail.com> wrote:

[snip]

> "Don't modify objects you don't own".
>
> A piece of code that modifies objects it does not own creates a coupling
> with those modifications and anything using that piece of code.
>
> This coupling creates a dependency of those modifications to all the
> dependencies of the code that exists in that codebase. Dependency of
> those modifications is maximized to every piece of code that uses the
> module that has modified them. Sometimes dependencies may even collide.
> For example, one piece of code may create Element.prototype.hide, and
> another piece of code may create a different Element.prototype.hide.
>
> Instead, a separate interface should be created. The interface can be as
> simple as a function. For example: hideElement( el ).
>
> A fair exception to that rule would be for adding or fixing properties
> that are either not yet implemented, or do not function as specified in
> the standard.
>
> if(!String.prototype.trim) {
>    // Patch for missing ES5 method.
>
> }

Just to be fair, you should mention, that augmenting (build-in, any)
objects in dynamic language with mutable objects - is in ideology of
such language. So, everyone chooses. You can *suggest* do not
augmenting "not own" object (with providing serious reason, which is
still just your meaning), but not statement this as rule.

For do not repeat myself: <URL:
http://groups.google.ru/group/comp.lang.javascript/browse_thread/thread/b5d5cf808c064462/bbfb83eb82ef9b41?hl=en#bbfb83eb82ef9b41>
and there's also link to other similar topic.

The only (the only.) reason - is using 3rd-party code, combined in
your application. But from this point of you, what exactly you are
afraid of - "another piece of code may create a different
Element.prototype.hide" - with the same success "another piece of code
may create a different hideElement( el )" which you suggest as a
"workaround", there's no any difference.

So, again, it's absolutely normal to augmenting objects in ES,
providing good documentation of what have you augmented (and for whole
code in general).

If you still wanna to write this as a rule, please mentioned, that
it's not the rule, but *just your own suggestion and own meaning*,
meanwhile other people can choose different (good) way augmenting
object and write in OOP-style such as `string.capitalize()' instead of
long ugly `Ext.util.Format.capitalize(string)'. Especially in own
project.

/ds

Asen Bozhilov

unread,
Dec 27, 2009, 6:38:22 AM12/27/09
to
Dmitry A. Soshnikov wrote:

> If you still wanna to write this as a rule, please mentioned, that
> it's not the rule, but *just your own suggestion and own meaning*,
> meanwhile other people can choose different (good) way augmenting
> object and write in OOP-style such as `string.capitalize()' instead of
> long ugly `Ext.util.Format.capitalize(string)'. Especially in own
> project.

You are absolutely right, but augmentation Object.prototype can be
harmful and confused. If implementations use native object produced
via `new Object()` as a VO and internal [[Prototype]] refer
Object.prototype, any augmentation of `object' referred from
Object.prototype can be harmful and confused. See below:

Object.prototype.x = 10;
var x = null;
(function()
{
window.alert(x);
}());

Expected value of `x` is `null`, but if VO is implement as a native
object value of `x` will be 10. Because:

| 10.1.4 Scope Chain and Identifier Resolution
| 1. Get the next object in the scope chain.
| If there isn't one, go to step 5.

In that case next object is VO/AO associated with EC created from
anonymous function.

| 2. Call the [[HasProperty]] method of Result(1),
| passing the Identifier as the property.

[[HasProperty]] lookup in prototype chain and will be return `true` in
that case.

| 3. If Result(2) is true, return a value of type Reference
| whose base object is Result(1) and whose property name
| is the Identifier.

{base : VO, propertyName : x};

So in my case *expected* value is primitive number value 10.

See and next example in Firefox 3.5:

Object.prototype.x = 10;
(function()
{
window.alert(x); //10 expected ReferenceError
}());

window.alert(this instanceof Object); //false
window.alert(this.__proto__ === Object.prototype); //false

How it is implement Global Object in Firefox 3.5? We can see Global
Object does not refer from internal [[Prototype]] object referred from
Object.prototype. And we can see that `object' doesn't inherit in
explicit way from Object.prototype. The question is, how it is
implement that object?

Regards.

Thomas 'PointedEars' Lahn

unread,
Dec 27, 2009, 7:36:40 AM12/27/09
to
David Mark wrote:

> Thomas 'PointedEars' Lahn wrote:
>> David Mark wrote:
>> > RobG wrote:


>> >> Garrett Smith wrote:
>> >> > Replace: "</" + "script>"
>> >> > with: "<\/script>";
>> >> > Replace: "</td>";
>> >> > with: "<\/td>";
>> >>
>> >> I don't understand the issue here, is it specifically with the TD end
>> >> tag? Or is it more generally with end tags in HTML sent as an XHR
>> >> response?
>> >
>> > No, it refers to markup in script (e.g. document.write calls).

>> [...]


>> > Nothing to do with the tag type.
>>
>> The *what*? I thought this was comp.lang.javascript, not
>> alt.scriptkiddie.misc.
>
> The type of tag serialized in the string (e.g. TD vs. SCRIPT). Are
> you proposing to refer to these as *elements*?

TD is one *element* type, SCRIPT is another.

<http://www.w3.org/TR/html4/intro/sgmltut.html#h-3.2.1>

> I think not as we are talking about just one (ending) tag (not both).

Iff you had meant "tag type" to distinguish between start tags and *end*
tags, which AIUI you have not, then that would have been acceptable. The
term would be potentially unclear, though.

Dmitry A. Soshnikov

unread,
Dec 27, 2009, 8:24:01 AM12/27/09
to

Thanks Asen, I appreciate your detailed explanations to me, although,
I sure know all of this ;) I mentioned that in my articles about scope
chain (chapter 4) and functions (chapter 5). It's sure well known fact
that in some versions of Spidermonkey Global object has
`Object.prototype' in it's prototype chain. Moreover, as you know,
special object created for NFE (named function expression) also
inherits (and fairly - by the ECMA-262-3) from the `Object.prototype'.
This situation is also taking place in Blackberry implementation,
where even simple activation object can inherit from
`Object.prototype'.

But if you carefully I mentioned it myself in link I gave above in
previous post. And till we haven't control of {DontEnum} (in
ECMA-262-5 - [[Enumerable]]), augmenting of `Object.prototype' as a
bad idea goes without saying and there's no reason to mention that
explicitly ;)

> window.alert(this instanceof Object); //false
> window.alert(this.__proto__ === Object.prototype); //false
>
> How it is implement Global Object in Firefox 3.5? We can see Global
> Object does not refer from internal [[Prototype]] object referred from
> Object.prototype. And we can see that `object' doesn't inherit in
> explicit way from Object.prototype. The question is, how it is
> implement that object?
>

I've already mentioned about that: <URL:
http://groups.google.ru/group/comp.lang.javascript/browse_thread/thread/2a5540da95f64f73/cea80a0fa53df9b0?hl=en&q=#52cce62f81fae1e6>

So the prototype chain of the Global in FF is the following (where
Object.prototype sure is):

// [xpconnect wrapped native prototype]
alert(this.__proto__);

// [object Global Scope Polluter]
alert(this.__proto__.__proto__);

// [object Object] - Object.prototype appears only now
alert(this.__proto__.__proto__.__proto__);

// null, end of the chain - Object.prototype.[[Prototype]]
alert(this.__proto__.__proto__.__proto__.__proto__);

/ds

David Mark

unread,
Dec 27, 2009, 11:48:07 AM12/27/09
to
On Dec 27, 7:36 am, Thomas 'PointedEars' Lahn <PointedE...@web.de>
wrote:

> David Mark wrote:
> > Thomas 'PointedEars' Lahn wrote:
> >> David Mark wrote:
> >> > RobG wrote:
> >> >> Garrett Smith wrote:
> >> >> > Replace: "</" + "script>"
> >> >> > with:    "<\/script>";
> >> >> > Replace: "</td>";
> >> >> > with:    "<\/td>";
>
> >> >> I don't understand the issue here, is it specifically with the TD end
> >> >> tag? Or is it more generally with end tags in HTML sent as an XHR
> >> >> response?
>
> >> > No, it refers to markup in script (e.g. document.write calls).
> >> [...]
> >> > Nothing to do with the tag type.
>
> >> The *what*?  I thought this was comp.lang.javascript, not
> >> alt.scriptkiddie.misc.
>
> > The type of tag serialized in the string (e.g. TD vs. SCRIPT).  Are
> > you proposing to refer to these as *elements*?
>
> TD is one *element* type, SCRIPT is another.
>
> <http://www.w3.org/TR/html4/intro/sgmltut.html#h-3.2.1>

Are you kidding?

>
> > I think not as we are talking about just one (ending) tag (not both).
>
> Iff you had meant "tag type" to distinguish between start tags and *end*
> tags, which AIUI you have not, then that would have been acceptable.

As you understand what? Was my explanation unclear?

> The
> term would be potentially unclear, though.

I don't think so in this case.

Eric Bednarz

unread,
Dec 27, 2009, 12:03:35 PM12/27/09
to
Garrett Smith <dhtmlk...@gmail.com> writes:

> Garrett Smith wrote:
>> Eric Bednarz wrote:
>>> Garrett Smith <dhtmlk...@gmail.com> writes:
>
> [...]
>
>>> Well, that didn’t take long. The document type declaration *is part of
>>> the prolog*, in both XML and SGML productions.
>> Maybe so, but for HTML, no comments and no prolog will trigger
>> quirks mode in IE. They should both be avoided for this reason.
> Correction:
> "comments and/or prolog will trigger quirks mode in IE."

Read again what I wrote. Without a prolog, you trigger quirks
mode. There is no “and/or” involved either, as comment declarations
preceding the document instance set are part of the prolog as well.

When you write

| * Use standards mode, with DOCTYPE first (no comment, xml prolog).

you probably mean “no XML declaration”. ‘Prolog’ is clearly defined by
XML 1.0, and it’s not what you want it to be.

(I can live with the term ‘comment’ in a practical HTML context, but
when pretending that it is useful to validate a HTML document against
its document type declaration subset, SGMLese should be used throughout
an ‘comment declaration’ would be correct.)

Garrett Smith

unread,
Dec 27, 2009, 2:45:04 PM12/27/09
to
Dmitry A. Soshnikov wrote:
> On Dec 27, 1:47 am, Garrett Smith <dhtmlkitc...@gmail.com> wrote:
>
> [snip]
>
>> "Don't modify objects you don't own".
[...]

>
> Just to be fair, you should mention, that augmenting (build-in, any)
> objects in dynamic language with mutable objects - is in ideology of
> such language. So, everyone chooses. You can *suggest* do not
> augmenting "not own" object (with providing serious reason, which is
> still just your meaning), but not statement this as rule.
>
> For do not repeat myself: <URL:
> http://groups.google.ru/group/comp.lang.javascript/browse_thread/thread/b5d5cf808c064462/bbfb83eb82ef9b41?hl=en#bbfb83eb82ef9b41>
> and there's also link to other similar topic.
>
> The only (the only.) reason - is using 3rd-party code, combined in
> your application. But from this point of you, what exactly you are
> afraid of - "another piece of code may create a different
> Element.prototype.hide" - with the same success "another piece of code
> may create a different hideElement( el )" which you suggest as a
> "workaround", there's no any difference.
>

For public API, a global hideElement would not be a good interface.
Instead, the interface would best be defined somewhere else.

When the method name is clearly defined as a property of an object, such as:

AcmeWidgets.dom.hideElement.

If the file "dom" is defined, say "dom.js", it would be clear what
depends on it.

If, OTOH, a public API that modifies built ins does not draw dependency
lines. Everything depends on everything. A public library that modifies
the built-ins can't really be trusted to work with other code.

// Where does this method belong? hostElementExtensions.js, or?
Element.prototype.hideElement -

Two different libraries could potentially define an
AcmeWidgets.dom.hideElement, but that would be explicit and immediately
obvious.

> So, again, it's absolutely normal to augmenting objects in ES,
> providing good documentation of what have you augmented (and for whole
> code in general).
>
> If you still wanna to write this as a rule, please mentioned, that
> it's not the rule, but *just your own suggestion and own meaning*,
> meanwhile other people can choose different (good) way augmenting
> object and write in OOP-style such as `string.capitalize()' instead of
> long ugly `Ext.util.Format.capitalize(string)'. Especially in own
> project.

I do not agree that util is a good name for a package. Packages or units
of code should be organized by usage pattern.

"util" is a kitchen sink.

Dmitry A. Soshnikov

unread,
Dec 27, 2009, 3:13:09 PM12/27/09
to
On Dec 27, 10:45 pm, Garrett Smith <dhtmlkitc...@gmail.com> wrote:

[snip]

> A public library that modifies


> the built-ins can't really be trusted to work with other code.
>

I understand, and told myself, that's this is the only (again - the
only.) reason. And from this point of view, you should mention this
just as a warning for authors of libraries, but not as a rule for
programming on ECMAScript.

Augmenting of built-ins is kind of additional "plug-ins", additional
functionality, which is treated as *own* which provides the way to
write more clear and elegant code. Just like host environment provides
additional objects to complete the program state, your augmenting
provides additional functionality.

There's no difference from the functional point of view - will you put
this code into the prototype of the built-in object, or will define
some global (or in your own namespace) function. But from the
ideological point of view, difference *is*.

And repeat, that dozen of 3rd-party, all of them (all of them!) can
provide the same global function `hideElement' and cause the name
conflict.

So, - only just a suggestion or a warning, but not the rule, 'cause
that's ECMAScript, but not a some static language. And for me, it's a
good practice to put functionality there where it's place (e.g. `trim'
or `capitalize' for strings in the String.prototype).

>
> > So, again, it's absolutely normal to augmenting objects in ES,
> > providing good documentation of what have you augmented (and for whole
> > code in general).
>
> > If you still wanna to write this as a rule, please mentioned, that
> > it's not the rule, but *just your own suggestion and own meaning*,
> > meanwhile other people can choose different (good) way augmenting
> > object and write in OOP-style such as `string.capitalize()' instead of
> > long ugly `Ext.util.Format.capitalize(string)'. Especially in own
> > project.
>
> I do not agree that util is a good name for a package. Packages or units
> of code should be organized by usage pattern.
>
> "util" is a kitchen sink.
>

That's not mine, that's real example from ExtJS library. I mentioned
that to show how the code can converts into the overloaded massive
long lines using everywhere things such as procedure-like style
`Ext.util.Format.capitalize(string)'. Yeah, influence of Java is
conclusive in ExtJS library ;)

/ds

Dr J R Stockton

unread,
Dec 27, 2009, 4:51:18 PM12/27/09
to
In comp.lang.javascript message <hh63qh$ee8$1...@news.eternal-
september.org>, Sat, 26 Dec 2009 14:47:43, Garrett Smith
<dhtmlk...@gmail.com> posted:

>Dr J R Stockton wrote:
>> In comp.lang.javascript message <hgp1oo$vee$1...@news.eternal-
>> september.org>, Mon, 21 Dec 2009 15:52:55, Garrett Smith
>> <dhtmlk...@gmail.com> posted:

>It may be worth considering assigning priority labels to certain things.
>For example: "Use valid HTML" an "Use standards mode" would be priority
>1 guidelines, while "Use efficient string concatenation techniques"
>might be a Priority 2, while

Much less than Priority 2, unless you can show a reasonable proportion
of common practical cases where optimising concatenation makes a
noticeable (not a measurable) difference to the time seen between
initiating action and visible results.


>>> * inconsistent return types
>>> Methods should return one type; returning null instead of an Object
>>> may be a fair consideration.
>> Where successful operation of a routine cannot return anything
>> resembling false, ISTM reasonable and useful to return something
>> resembling false if the routine has failed to do what was wanted.
>>
>
>Functions that return multiple type provide more variance to the caller.
>
>Sometimes this happens on accident, where the function was
>intended to return one type, but can return a value of a different type.
>
>Functions that return only one value type (including undefined) do not
>burden the caller with having to check the return type.
>
>It is something to look for in code where the function may, for example,
>return a number in one case and a string in another case.
>
>Functions that return multiple type have their place. A method might
>return an object, but return null if the operation failed. So it is not
>a rule, but something to consider when looking the code.

One does not need to check the return type if the mutually exclusive
return alternatives are to give something which will pass as false and
to give something which will not pass as false.

Result = FunctionOfAllSortsOfThings(......)
if (!Result) { ... /* it failed */ ... ; return }
// Code using good Result ...

Result = FunctionOfAllSortsOfThings(......)
if (Result) { /* Code using good Result */ ; return Answer }
// moaning & wailing

For an example, see
FAQ 4.2 How can I create a Date object from a String?

OTOH, my recently-posted Leading Zero function LZ takes care always to
return a string (unlike function LZ(N) { return N<10 ? "0" + N : N } );
then Y+LZ(M)+LZ(D) works as well for Oct-Dec as it does for Jan-Sep.


Really, the recommendation should be against functions returning
unexpected types.

>SRP The Single Responsibility Principle
> A class should have one, and only one, reason to change.
>OCP The Open Closed Principle
> You should be able to extend a classes behavior, without modifying it.
>LSP The Liskov Substitution Principle
> Derived classes must be substitutable for their base classes.
>DIP The Dependency Inversion Principle
> Depend on abstractions, not on concretions.
>ISP The Interface Segregation Principle
> Make fine grained interfaces that are client specific.

TMA.

Thomas 'PointedEars' Lahn

unread,
Dec 27, 2009, 8:04:18 PM12/27/09
to
David Mark wrote:

> Thomas 'PointedEars' Lahn wrote:
>> David Mark wrote:
>> > Thomas 'PointedEars' Lahn wrote:
>> >> David Mark wrote:
>> >> > RobG wrote:
>> >> >> Garrett Smith wrote:
>> >> >> > Replace: "</" + "script>"
>> >> >> > with: "<\/script>";
>> >> >> > Replace: "</td>";
>> >> >> > with: "<\/td>";
>> >> >>
>> >> >> I don't understand the issue here, is it specifically with the TD

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^


>> >> >> end tag? Or is it more generally with end tags in HTML sent as an

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^


>> >> >> XHR response?
>> >> > No, it refers to markup in script (e.g. document.write calls).
>> >> [...]
>> >> > Nothing to do with the tag type.

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^


>> >> The *what*? I thought this was comp.lang.javascript, not
>> >> alt.scriptkiddie.misc.
>> > The type of tag serialized in the string (e.g. TD vs. SCRIPT). Are

^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^


>> > you proposing to refer to these as *elements*?
>> TD is one *element* type, SCRIPT is another.
>>
>> <http://www.w3.org/TR/html4/intro/sgmltut.html#h-3.2.1>
>
> Are you kidding?

No. Have you read that part of the Specification carefully?

>> > I think not as we are talking about just one (ending) tag (not both).
>> Iff you had meant "tag type" to distinguish between start tags and *end*
>> tags, which AIUI you have not, then that would have been acceptable.
>
> As you understand what?

You were referring to TD and SCRIPT as different "type(s) of tag".

> Was my explanation unclear?

It was not only unclear, it was incorrect.


HTH

David Mark

unread,
Dec 27, 2009, 10:06:49 PM12/27/09
to
On Dec 27, 8:04 pm, Thomas 'PointedEars' Lahn <PointedE...@web.de>

No need.

>
> >> > I think not as we are talking about just one (ending) tag (not both).
> >> Iff you had meant "tag type" to distinguish between start tags and *end*
> >> tags, which AIUI you have not, then that would have been acceptable.
>
> > As you understand what?
>
> You were referring to TD and SCRIPT as different "type(s) of tag".

You misunderstand. They are different "types of tags" (as only the
ending tags of each are present in the serialization). If I had meant
element, I should have said element. :)

Garrett Smith

unread,
Dec 28, 2009, 12:25:35 AM12/28/09
to
Asen Bozhilov wrote:
> Dmitry A. Soshnikov wrote:
>
>> If you still wanna to write this as a rule, please mentioned, that
>> it's not the rule, but *just your own suggestion and own meaning*,
>> meanwhile other people can choose different (good) way augmenting
>> object and write in OOP-style such as `string.capitalize()' instead of
>> long ugly `Ext.util.Format.capitalize(string)'. Especially in own
>> project.
>
> You are absolutely right, but augmentation Object.prototype can be
> harmful and confused. If implementations use native object produced
> via `new Object()` as a VO and internal [[Prototype]] refer
> Object.prototype, any augmentation of `object' referred from
> Object.prototype can be harmful and confused. See below:
>
> Object.prototype.x = 10;
> var x = null;
> (function()
> {
> window.alert(x);
> }());
.....^

Move that paren inwards, to group the FunctionExpression, as:
(function(){})();

>
> Expected value of `x` is `null`, but if VO is implement as a native
> object value of `x` will be 10. Because:

[...]

If - VO - is a variable object, then it must have no [[Prototype]].

The prototype of teh global object is implementation-dependent.

In Blackberry9000, the activation object has a [[Prototype]]. That is a
severe bug.

The identifier - x - would be resolved on Object.prototype when the
scope chain was augmented "as if by the expression new Object()".

The three cases where this happens:-
1) FunctionExpression with Identifier (NFE)
2) catch clause
3) - with - statement.

(function(){


Object.prototype.x = 10;
var x = null;

with( 1 ) { alert( "with, x: " + x ); }

try {
throw.1;
} catch(ex) {
alert( "with, x: " + x );
}
})();

The issue with NFE and catch clause was observable in Firefox up until
around version 3.1.

Firefox 3.5:-
"with, x: 10"
"catch, x: null"

Garrett Smith

unread,
Dec 28, 2009, 1:25:55 AM12/28/09
to
Dmitry A. Soshnikov wrote:
> On Dec 27, 10:45 pm, Garrett Smith <dhtmlkitc...@gmail.com> wrote:
>
> [snip]
>
>> A public library that modifies
>> the built-ins can't really be trusted to work with other code.
>>
>
> I understand, and told myself, that's this is the only (again - the
> only.) reason. And from this point of view, you should mention this
> just as a warning for authors of libraries, but not as a rule for
> programming on ECMAScript.
>
[...]

What I have as draft includes most of what I wrote in the last message.
The advice to create a top-level function advise creating a method as a
member of the global object, having the same problems.

Instead, a separate interface should be created. The interface should be
clearly defined, cohesive, and unlikely to conflict with other objects
that use the system.

>
>>> So, again, it's absolutely normal to augmenting objects in ES,
>>> providing good documentation of what have you augmented (and for whole
>>> code in general).
>>> If you still wanna to write this as a rule, please mentioned, that
>>> it's not the rule, but *just your own suggestion and own meaning*,
>>> meanwhile other people can choose different (good) way augmenting
>>> object and write in OOP-style such as `string.capitalize()' instead of
>>> long ugly `Ext.util.Format.capitalize(string)'. Especially in own
>>> project.

You can do that, but it doesn't fit what I think of as OOP. It is an
abstraction using inheritance, but it lacks encapsulation and modularity.

It is more like a reverse-inheritance type of scheme that changes String
in a way that may or may not be forwards-compatible. Object.create, for
a coincidental example, is now a built-in method, but exists as a
user-defined method in some codebases.

>> I do not agree that util is a good name for a package. Packages or units
>> of code should be organized by usage pattern.
>>
>> "util" is a kitchen sink.
>>
>
> That's not mine, that's real example from ExtJS library. I mentioned
> that to show how the code can converts into the overloaded massive
> long lines using everywhere things such as procedure-like style
> `Ext.util.Format.capitalize(string)'. Yeah, influence of Java is
> conclusive in ExtJS library ;)
>

Util is not a descriptive package name.

Not for Java, and not for Ext.js.

Take a look at java.util and please tell me Date have to do with Arrays
or TimerTask? Nothing, right?

Well javascript borrowed from Java, too. We've got the poor Date class
and Math. Many of the Math properties could have been moved to Number
and/or Number.prototype, depending on the property. Math.floor could be
Number.prototype.floor(), We could have 3.45.round() instead of
Math.round(3.45). Number.PI, Number.max(10, 11, 12). Well that is all
fiction made up but for me it makes way more sense than having a
separated Math class.

It seems worth considering changing that to Ext.string, and adding the
capitalize method to it.

Ext.string.capitalize("foo");

Collisions to that would be deliberate and you would know right off what
the capitalize method is, where it is defined, and not have to worry who
buggered String.prototype or if the buggering was a dual- action effort
on part of multiple third party libraries.

The capitalize method would not localize consistently, as noted recently
on ES-Discuss[1]. If the string is translated and included literally,
this doesn't occur.

var msg = "${req.msg}";

In ES5, a property can be defined has having [[Writable]] = false.

This can happen in Object.create, with Object.defineProperty, setting
writable: false.

Object.freeze seals an object and makes its properties unmodifiable by
setting [[Writable]] to false.

Creating a sealed object eliminates the possibility for conflicts with
another Ext.string.capitalize.

[1]https://mail.mozilla.org/pipermail/es-discuss/2009-December/010482.html

Dmitry A. Soshnikov

unread,
Dec 28, 2009, 4:49:10 AM12/28/09
to
On Dec 28, 9:25 am, Garrett Smith <dhtmlkitc...@gmail.com> wrote:
> Dmitry A. Soshnikov wrote:
> > On Dec 27, 10:45 pm, Garrett Smith <dhtmlkitc...@gmail.com> wrote:
>
> > [snip]
>
> >> A public library that modifies
> >> the built-ins can't really be trusted to work with other code.
>
> > I understand, and told myself, that's this is the only (again - the
> > only.) reason. And from this point of view, you should mention this
> > just as a warning for authors of libraries, but not as a rule for
> > programming on ECMAScript.
>
> [...]
>
> What I have as draft includes most of what I wrote in the last message.
> The advice to create a top-level function advise creating a method as a
> member of the global object, having the same problems.
>
> Instead, a separate interface should be created. The interface should be
> clearly defined, cohesive, and unlikely to conflict with other objects
> that use the system.
>

Formally, there's no full protected "interface" from this point of
view. Will you name it `MyVeryOwnNamespace', and tomorrow, the same
name will be in all `libraries' and in ES itself. So, naming
collisions should not be treated as the main reason.

>
>
> >>> So, again, it's absolutely normal to augmenting objects in ES,
> >>> providing good documentation of what have you augmented (and for whole
> >>> code in general).
> >>> If you still wanna to write this as a rule, please mentioned, that
> >>> it's not the rule, but *just your own suggestion and own meaning*,
> >>> meanwhile other people can choose different (good) way augmenting
> >>> object and write in OOP-style such as `string.capitalize()' instead of
> >>> long ugly `Ext.util.Format.capitalize(string)'. Especially in own
> >>> project.
>
> You can do that, but it doesn't fit what I think of as OOP. It is an
> abstraction using inheritance, but it lacks encapsulation and modularity.
>

What exactly do you mean? Please explain.

> It is more like a reverse-inheritance type of scheme that changes String
> in a way that may or may not be forwards-compatible. Object.create, for
> a coincidental example, is now a built-in method, but exists as a
> user-defined method in some codebases.
>
> >> I do not agree that util is a good name for a package. Packages or units
> >> of code should be organized by usage pattern.
>
> >> "util" is a kitchen sink.
>
> > That's not mine, that's real example from ExtJS library. I mentioned
> > that to show how the code can converts into the overloaded massive
> > long lines using everywhere things such as procedure-like style
> > `Ext.util.Format.capitalize(string)'. Yeah, influence of Java is
> > conclusive in ExtJS library ;)
>
> Util is not a descriptive package name.
>
> Not for Java, and not for Ext.js.
>
> Take a look at java.util and please tell me Date have to do with Arrays
> or TimerTask? Nothing, right?
>
> Well javascript borrowed from Java, too. We've got the poor Date class
> and Math. Many of the Math properties could have been moved to Number
> and/or Number.prototype, depending on the property. Math.floor could be
> Number.prototype.floor(), We could have 3.45.round() instead of
> Math.round(3.45). Number.PI, Number.max(10, 11, 12). Well that is all
> fiction made up but for me it makes way more sense than having a
> separated Math class.
>

Yeah, it could easily be `3.45.round()' instead of `Math' I agree.

> It seems worth considering changing that to Ext.string, and adding the
> capitalize method to it.
>
> Ext.string.capitalize("foo");
>
> Collisions to that would be deliberate and you would know right off what
> the capitalize method is, where it is defined, and not have to worry who
> buggered String.prototype or if the buggering was a dual- action effort
> on part of multiple third party libraries.
>

But there's no difference, will somebody put `capitalize' into the
`String.prototype' or will define own `Ext' or `Ext.string' namespace
- tomorrow, it can easily appear in all other libraries and in ES
itself. So, don't use name collision as a reason.

Moreover, I tell, people which use libraries think vice versa - they
think: "we don't not modify String.prototype as we're using 3rd-party
frameword, which can put tomorrow (in the next version) `capitalize'
method into it. So let's make our own namespace such as
OutSuperDuperNamespace.string and put `capitalize' there." And
tomorrow, OMG, that framework provides the same
`OutSuperDuperNamespace' and even `OutSuperDuperNamespace.string'
breaking down all the project. So, that's not the reason.

> The capitalize method would not localize consistently, as noted recently
> on ES-Discuss[1]. If the string is translated and included literally,
> this doesn't occur.
>

I understand, but that's completely another question, and doesn't
touch the discussing topic.

>
> In ES5, a property can be defined has having [[Writable]] = false.
>
> This can happen in Object.create, with Object.defineProperty, setting
> writable: false.
>
> Object.freeze seals an object and makes its properties unmodifiable by
> setting [[Writable]] to false.
>
> Creating a sealed object eliminates the possibility for conflicts with
> another Ext.string.capitalize.
>

Yep, thanks, I've also read ES-5 spec already. So, you're moving to
the way I told - better to suggest to use some static language in such
case, but not the language with dynamic mutable objects and statement
as a rule: "Do not touch your own objects".

So, if you'll write something like: "Remember that augmenting built-
ins may cause naming conflicts, bla-bla... but the same can be with
any other name in the program - no matter where it's - in global or in
own namespace" - that's will be normal. It will sound like suggesting
from your own opinion.

But if you'll write - "Augmenting built-ins - is a bad practice" -
that will be categorical and wrong, and I can statement, that person
which spread that not completely understand the goal of dynamic
languages (I do not mean exactly you, I'm telling abstractly now).

/ds

Thomas 'PointedEars' Lahn

unread,
Dec 28, 2009, 5:41:41 AM12/28/09
to
David Mark wrote:

> Thomas 'PointedEars' Lahn wrote:
>> David Mark wrote:
>> > Thomas 'PointedEars' Lahn wrote:
>> >> David Mark wrote:
>> >> > Thomas 'PointedEars' Lahn wrote:
>> >> >> David Mark wrote:
>> >> >> > RobG wrote:
>> >> >> >> Garrett Smith wrote:
>> >> >> >> > Replace: "</" + "script>"
>> >> >> >> > with: "<\/script>";
>> >> >> >> > Replace: "</td>";
>> >> >> >> > with: "<\/td>";
>> >> >> >>
>> >> >> >> I don't understand the issue here, is it specifically

>> ^^^^^^^^^^^^^^^^^^
>> >> >> >> with the TD end tag? Or is it more generally with end tags
>> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>> >> >> >> in HTML sent as an XHR response?
>> ^^^^^^^


>> >> >> > No, it refers to markup in script (e.g. document.write calls).
>> >> >> [...]
>> >> >> > Nothing to do with the tag type.
>> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

>> >> >> [...]


>> >> > The type of tag serialized in the string (e.g. TD vs. SCRIPT).

>> ^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^
>> >> > Are you proposing to refer to these as *elements*?


>> >> TD is one *element* type, SCRIPT is another.
>> >>
>> >> <http://www.w3.org/TR/html4/intro/sgmltut.html#h-3.2.1>
>> > Are you kidding?
>> No. Have you read that part of the Specification carefully?
>
> No need.

Apparently there is.



>> >> > I think not as we are talking about just one (ending) tag (not
>> >> > both).
>> >> Iff you had meant "tag type" to distinguish between start tags and
>> >> *end* tags, which AIUI you have not, then that would have been
>> >> acceptable.
>> > As you understand what?
>> You were referring to TD and SCRIPT as different "type(s) of tag".
>
> You misunderstand. They are different "types of tags" (as only the
> ending tags of each are present in the serialization). If I had meant
> element, I should have said element. :)

If so, it was easy to misunderstand, as in "potentially unclear".

> They are different "types of tags" (as only the
> ending tags of each are present in the serialization). If I had meant
> element, I should have said element. :)

So you meant "e.g. </td> vs. </script>" (not "e.g. TD vs. SCRIPT"), and
called the former "type(s) of tags" or "tag type", which is potentially
unclear after all?

For if anything could be called "type of tag" or "tag type", it is the
difference between start tag and end tag, and in that sense both `</td>'
and `</script>' are of the same type. But those who did not know the
correct terminology could, mislead by your statement, assume that what you
call "type of tag" or "tag type" would refer to what is correctly called
the element type.

You garbled the quotations; please learn to quote. (Not using Google
Groups for posting would help a lot there.)


PointedEars
--
Anyone who slaps a 'this page is best viewed with Browser X' label on
a Web page appears to be yearning for the bad old days, before the Web,
when you had very little chance of reading a document written on another
computer, another word processor, or another network. -- Tim Berners-Lee

Asen Bozhilov

unread,
Dec 28, 2009, 8:22:25 AM12/28/09