Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Code Guidelines

104 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
to
Garrett Smith wrote:

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

What is the difference between:

typeof function(){}();

(function(){}());

(function(){})();

Please explain.


> > 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]].

But documentation permit VO to have [[Prototype]] from:

| 10.1.4 Scope Chain and Identifier Resolution

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

I don't think that is a bug in Blackberry9000, because documentation
permit that behavior. That is implementation-dependent too.

Btw 1: In FAQ link above "BlackBerry JavaScript Reference"
<URL: http://docs.blackberry.com/en/developers/deliverables/8861/>
Links in that page ares broken. They redirect me to:
<URL: http://docs.blackberry.com/404error.jsp>

Proper URL is:
<URL: http://docs.blackberry.com/en/developers/deliverables/11849/>

Btw 2: Why not include in "Code Guidelines" `delete` operator over a
host objects, because host object can implement own internal
[[Delete]] method and using `delete` operator for host objects can be
error-prone.

Regards.

Lasse Reichstein Nielsen

unread,
Dec 28, 2009, 9:20:01 AM12/28/09
to
Asen Bozhilov <asen.b...@gmail.com> writes:

> Garrett Smith wrote:
>> Asen Bozhilov wrote:
>>
>> Move that paren inwards, to group the FunctionExpression, as:
>> (function(){})();
>
> What is the difference between:
>
> typeof function(){}();
>
> (function(){}());
>
> (function(){})();
>
> Please explain.

The last two are equivalent. The first evaluates to a string instead
of the undefined value :)

I would recommend (function(){})() over (function(){}()) for two reasons:
readability (it's easier to see the grouping) and convention (it's easier
to recognize what's going on). There is no technical reason to prefer one
over the other.

/L
--
Lasse Reichstein Holst Nielsen
'Javascript frameworks is a disruptive technology'

Dmitry A. Soshnikov

unread,
Dec 28, 2009, 9:37:10 AM12/28/09
to
On Dec 28, 5:20 pm, Lasse Reichstein Nielsen <lrn.unr...@gmail.com>
wrote:

> Asen Bozhilov <asen.bozhi...@gmail.com> writes:
> > Garrett Smith wrote:
> >> Asen Bozhilov wrote:
>
> >> Move that paren inwards, to group the FunctionExpression, as:
> >> (function(){})();
>
> > What is the difference between:
>
> > typeof function(){}();
>
> > (function(){}());
>
> > (function(){})();
>
> > Please explain.
>
> The last two are equivalent. The first evaluates to a string instead
> of the undefined value :)
>
> I would recommend (function(){})() over (function(){}()) for two reasons:
> readability (it's easier to see the grouping) and convention (it's easier
> to recognize what's going on). There is no technical reason to prefer one
> over the other.
>

Meanwhile, there's a test case, when that two forms will not be
equivalent. It's related to automatic semicolon insertion when
semicolon is not inserted in case of one function expression form:

var foo = function () {
alert(arguments[0]);
}

(function () {return 'x';}())

In this case we've "forgot" semicolon after FE referenced by `foo'
variable, try to run it, you'll see the result.

var foo = function () {
alert(arguments[0]);
}

(function () {return 'x';})()

Meanwhile, this form (where we've also "forgot" semicolon after `foo')
will throw an exception.

Sure, this case should be changed to the following with semicolons:

var foo = function () {
alert(arguments[0]);
};

(function () {return 'x';})();

In this form the grouping operator of the second one FE is not treated
as brackets of the call expression, as it was in two previous cases.

/ds

Garrett Smith

unread,
Dec 28, 2009, 9:05:03 PM12/28/09
to
Lasse Reichstein Nielsen wrote:
> Asen Bozhilov <asen.b...@gmail.com> writes:
>
>> Garrett Smith wrote:
>>> Asen Bozhilov wrote:
>>>
>>> Move that paren inwards, to group the FunctionExpression, as:
>>> (function(){})();
>> What is the difference between:
>>
>> typeof function(){}();
>>
>> (function(){}());
>>
>> (function(){})();
>>
>> Please explain.
>
> The last two are equivalent. The first evaluates to a string instead
> of the undefined value :)
>
> I would recommend (function(){})() over (function(){}()) for two reasons:
> readability (it's easier to see the grouping) and convention (it's easier
> to recognize what's going on). There is no technical reason to prefer one
> over the other.
>
Right. All three are valid ExpressionStatement.

I had (mis?)believed a parse error in a browser, and so have always that
approach. I can't create an error by wrapping the entire thing in
parens. Safari 2 is happy with:-

javascript: (function(){alert(1)}());

But it is also important to remember that an ExpressionStatement can't
begin with `function` keyword because that would be ambiguous with a
FunctionDeclaration. Nor can an expression statement begin with `{`, as
that would be ambiguous with a Block, and so:-

(function(){}());

- is valid, but:-

function(){}(); // SyntaxError.

- is not.

Garrett Smith

unread,
Dec 28, 2009, 11:49:05 PM12/28/09
to
Asen Bozhilov wrote:
> Garrett Smith wrote:
>> Asen Bozhilov wrote:
>>
>> Move that paren inwards, to group the FunctionExpression, as:
>> (function(){})();
>
> What is the difference between:
>
> typeof function(){}();
>
> (function(){}());
>
> (function(){})();
>
> Please explain.
>
>
>>> 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]].
>
> But documentation permit VO to have [[Prototype]] from:
>
> | 10.1.4 Scope Chain and Identifier Resolution
> | 2. Call the [[HasProperty]] method of Result(1), passing the
> Identifier as the property.
>
> I don't think that is a bug in Blackberry9000, because documentation
> permit that behavior. That is implementation-dependent too.
>

That actually seems to be correct.

A program cannot access the activation object, but there's nowhere I
read that activation object cannot have a [[Prototype]].

If the variable object has a [[Prototype]], then identifier resolution
behaves differently. We disucssed this before...

http://groups.google.com/group/comp.lang.javascript/browse_thread/thread/ec2ffbc979c65cc4/

Can Activation Object have a [[Prototype]]?

I'm posting this question to es-discuss. ES5 has what is called "Lexical
Environment" and I do not know if [[Prototype]] is explicitly forbidden
for that object. Am I missing something?

> Btw 1: In FAQ link above "BlackBerry JavaScript Reference"
> <URL: http://docs.blackberry.com/en/developers/deliverables/8861/>
> Links in that page ares broken. They redirect me to:
> <URL: http://docs.blackberry.com/404error.jsp>
>

Oh, that's no good.

Ah, thanks, fixed locally.

> Btw 2: Why not include in "Code Guidelines" `delete` operator over a
> host objects, because host object can implement own internal
> [[Delete]] method and using `delete` operator for host objects can be
> error-prone.
>

Certainly it can be. IE throws errors with delete on window properties,
though not on global variables.

var x = 10;
this.y = 11;
delete x; // false;
delete y: // error.

Asen Bozhilov

unread,
Dec 29, 2009, 9:08:51 AM12/29/09
to
Dmitry A. Soshnikov wrote:

> var foo = function () {
>   alert(arguments[0]);
>
> }
>
> (function () {return 'x';})()
>
> Meanwhile, this form (where we've also "forgot" semicolon after `foo')
> will throw an exception.

Thank for that example. It can be very hard to catch that, especially
if returned value from `foo` is a reference to object which have
internal [[Call]] method.

var foo = function () {

return arguments[0];
}

(function () {return 'x';})();

Expected behavior in unexpected way.

var foo = function () {

return function(){};
}

(function () {return 'x';})();

There are no error, and absolutely unexpected behavior in first look,
but actually is it normal and expected behavior.

Dmitry A. Soshnikov

unread,
Dec 29, 2009, 9:14:16 AM12/29/09
to

Yep, absolutely right.

/ds

Asen Bozhilov

unread,
Dec 29, 2009, 11:43:21 AM12/29/09
to
Garrett Smith wrote:

> Certainly it can be. IE throws errors with delete on window properties,
> though not on global variables.
>
> var x = 10;
> this.y = 11;
> delete x; // false;
> delete y: // error.

^;
Typo correction ;~)

More suggestions for "Code Guidelines".

Doesn't have information:
- About `11.10 Binary Bitwise Operators` and how they converted
operands `ToInt32`. Which mean, with `Bitwise Operators` can loose
precision. See below:

var x = Math.pow(2, 30);
window.alert(x); //1073741824
window.alert(x & x); //1073741824

x = Math.pow(2, 34);
window.alert(x); //17179869184
window.alert(x & x); //0

- About comparison of NaN values:

window.alert(NaN === NaN); //false
window.alert(isNaN(NaN)); //true

- In which cases primitive values will be converted automatically
ToObject and ToObject with which values throw TypeError.

window.alert('str'.concat);

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

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

- About for-in loops. That is related with augmentation of built-in
objects prototype chain and with my previous item.

try {
for (var i in null);
}catch(e) {
window.alert(e);
}

I'm cannot found browser ECMA-262 implementation which follow the
specification in `12.6.4 The for-in Statement` step 3 in `for
( LeftHandSideExpression in Expression ) Statement` and step 4 in `for
( var VariableDeclarationNoIn in Expression )`
| Call ToObject(GetValue(Expression))

Only in "DMD Script" i get a expected behavior in relation to ECMA
262-3 12.6.4.


Garrett Smith

unread,
Dec 29, 2009, 1:48:01 PM12/29/09
to
Asen Bozhilov wrote:
> Garrett Smith wrote:
>
>> Certainly it can be. IE throws errors with delete on window properties,
>> though not on global variables.
>>
>> var x = 10;
>> this.y = 11;
>> delete x; // false;
>> delete y: // error.
> ^;
> Typo correction ;~)
>
I added under DOM section:

Host Objects:
* Operators:
- DO not use delete operator with host object (IE Errors)
* Accessing Host objects that are or can be ActiveX objects.
These may include, but are not limited to:
- Disconnected nodes (node.offsetParent)
- XMLHttpRequest methods
- style filters

ES5 requires all Host object to implement HasProperty, along with
[[Get]], [[Delete]], [[DefaultValue]], et al (see Table 8). This is a
big step in the right direction and I'm optimistic of more such things
from the committee.

> More suggestions for "Code Guidelines".
>
> Doesn't have information:
> - About `11.10 Binary Bitwise Operators` and how they converted
> operands `ToInt32`. Which mean, with `Bitwise Operators` can loose
> precision. See below:
>

I don't often see such mistake. The last I remember seeing it was John
Resig's blog around 2007 or so, related to failed ES4.

If you have an example of a piece of code that suffered a bug because of
it, I'd be happy to include it.

It would be worth recommending:-

For numeric conversion, use unary + operator, for parsing numbers from
strings, use parseInt(s, radix);

> window.alert(NaN === NaN); //false
> window.alert(isNaN(NaN)); //true
>
> - In which cases primitive values will be converted automatically
> ToObject and ToObject with which values throw TypeError.
>
> window.alert('str'.concat);
>
> try {
> null.foo;
> }catch(e) {
> window.alert(e instanceof TypeError); //true
> }
>
> try {
> with(undefined);
> }catch(e) {
> window.alert(e instanceof TypeError); //true
> }
>

I don't understand. What you are suggesting?

> - About for-in loops. That is related with augmentation of built-in
> objects prototype chain and with my previous item.
>
> try {
> for (var i in null);
> }catch(e) {
> window.alert(e);
> }
>
> I'm cannot found browser ECMA-262 implementation which follow the
> specification in `12.6.4 The for-in Statement` step 3 in `for
> ( LeftHandSideExpression in Expression ) Statement` and step 4 in `for
> ( var VariableDeclarationNoIn in Expression )`
> | Call ToObject(GetValue(Expression))
>
> Only in "DMD Script" i get a expected behavior in relation to ECMA
> 262-3 12.6.4.
>

No TypeError, huh? You might want to mention that observation on
es-discuss mailing list. If the major script engines are not complying
with the spec, either the spec should change or the implementations
should.

Dmitry A. Soshnikov

unread,
Dec 29, 2009, 2:40:08 PM12/29/09
to
On Dec 29, 7:43 pm, Asen Bozhilov <asen.bozhi...@gmail.com> wrote:

[snip]

>
>   I'm cannot found browser ECMA-262 implementation which follow the
> specification in `12.6.4 The for-in Statement` step 3 in `for
> ( LeftHandSideExpression in Expression ) Statement` and step 4 in `for
> ( var VariableDeclarationNoIn in Expression )`
>   | Call ToObject(GetValue(Expression))
>
>   Only in "DMD Script" i get a expected behavior in relation to ECMA
> 262-3 12.6.4.

Yep, implementations know about that. For example, Spidermonkey
justifies that like "web JS" ;)

/*
* Enumerating over null and undefined gives an empty enumerator.
* This is contrary to ECMA-262 9.9 ToObject, invoked from step 3 of
* the first production in 12.6.4 and step 4 of the second production,
* but it's "web JS" compatible.
*/

http://code.google.com/p/v8/source/browse/trunk/src/arm/codegen-arm.cc#1747

V8, e.g. like this (referencing on Spidermonkey and WebKit):

// Both SpiderMonkey and kjs ignore null and undefined in contrast
// to the specification. 12.6.4 mandates a call to ToObject.

http://code.google.com/p/v8/source/browse/trunk/src/arm/codegen-arm.cc#1747

/ds

Dmitry A. Soshnikov

unread,
Dec 29, 2009, 2:42:10 PM12/29/09
to
On Dec 29, 10:40 pm, "Dmitry A. Soshnikov"
<dmitry.soshni...@gmail.com> wrote:

[snip]

> Spidermonkey
>
> http://code.google.com/p/v8/source/browse/trunk/src/arm/codegen-arm.c...
>

Oops, sorry, wrong link. This one is correct for Spidermonkey:

<URL: http://mxr.mozilla.org/mozilla/source/js/src/jsiter.c#352>

/ds

Asen Bozhilov

unread,
Dec 29, 2009, 4:01:05 PM12/29/09
to
Garrett Smith wrote:

> If you have an example of a piece of code that suffered a bug because of
> it, I'd be happy to include it.

No. I'm not have any example from production code or popular library.
You're correct about that. Is not very often *error*.

> I don't understand. What you are suggesting?

The main goal of my previous post is related to "Implicit type
conversion" and "Automatically type conversion". Perhaps for that will
be good to have separate article, if doesn't have yet.

Regards.

Dmitry A. Soshnikov

unread,
Dec 29, 2009, 5:06:57 PM12/29/09
to
On Dec 29, 9:48 pm, Garrett Smith <dhtmlkitc...@gmail.com> wrote:

[snip]

>     - DO not use delete operator with host object (IE Errors)

Again, too categorical. If you know what you are doing, it can be
useful to use `delete'. Better to write "Be carefull using delete
operator with host objects because... (IE Errors)".

/ds

Garrett Smith

unread,
Dec 29, 2009, 6:24:36 PM12/29/09
to

There is an faq note about type conversion by Cornford.

http://www.jibbering.com/faq/faq_notes/type_convert.html

I have worked on cleaning that document up to have HTML 4.01 strict at:-

/faq/notes/type-conversion/

Garrett Smith

unread,
Dec 29, 2009, 6:56:31 PM12/29/09
to

I suppose the same is true for `in` operator, to a lesser extent. That
can fail in a few cases.

"ownerDocument" in document; // false in BB9k its there.
"9999" in document.styleSheets; // true in IE.

Which Host object in IE does delete work on? I know it fails with
window, but have not tried with other objects.

Garrett Smith

unread,
Dec 29, 2009, 8:04:03 PM12/29/09
to

Modifying the public interface of String changes Strings to be something
different. Any code that uses String now has that change.

Creating a separate file for string utils does not impose a global
change dependency.

Putting the captilize function in a separate separates the concern so
that only as many modules as necessary depend on that module.

This minimizes dependencies, which makes code change possible. The less
dependency you have, the easier it is to change.

There is no room for confusion in the intended interface with other
modules.

Modifying built-ins prototypes maximizes the dependency. Everything has
String.prototype, right? Well, now if you modify that, then everything
has that modification.

Instead, the code should be doing the opposite; instead of maximizing
scope, it should be minimizing scope. That way, when somebody wants to
change it, he can. And (bonus) if he did a good job at minimizing
dependency, it's easy (and he doesen't have to retest the entire system).

First off, who creates a namespace like "OutSuperDuperNamespace". Then,
of those people, who then goes on to include *another* library that also
the same (fruity) namespace?

A sensible developer would organize the coe into modules. Obviously
"DOM" (in any case) would be likely to conflict on global level. I use,
for example, APE.dom.

And that way, there is no need to worr about a getPosition or getCoords,
or getStyle function. I have the DOM module, which is all about the dom,
then within that there are modules for style, position, events, and each
aspect is organized so that it is pretty narrow, small and easy to test.

That is modularity.

>> 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".
>

"Do not touch your own objects" sounds like the exact opposite of what I
meant.

> 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.
>

It's more than conflicts. Conflicts cause errors, but rigid APIs with a
lot of interdependency make change hard.

> 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).

I'm not completely sure what that means.

kangax

unread,
Dec 29, 2009, 10:34:20 PM12/29/09
to
On 12/25/09 6:32 PM, Thomas 'PointedEars' Lahn wrote:
> Garrett Smith wrote:

[...]

>>> 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"
^^^^^^^^^^^^^^^^^
Are you sure about that?

<http://www.w3.org/TR/REC-html40/sgml/dtd.html>

[...]

--
kangax

Dmitry A. Soshnikov

unread,
Dec 30, 2009, 3:59:36 AM12/30/09
to

Nope, it hasn't. Sorry, bug that's just a demagogy. The code will have
that changes when it will *use* that changes. And please, show me, how
many changes you'll need to do for modifying method name from e.g.
`capitalize' to `capitalizeMethod', if that method uses in e.g. 10
files and doesn't matter where it is described - in
`String.prototype.capitalize' or in
`VeryOwnStringNamespace.capitalize' How many? Please count and tell
me. So, please, do not use demagogy as the logical arguments.

> Creating a separate file for string utils does not impose a global
> change dependency.
>

Does. Absolutely the same. Take the example above - please count the
changes you need - in *real* dependency - when some code *uses* that
name: 'string'.capitalize() or VeryOwnStringNamespace.capitalize
('string').

> Putting the captilize function in a separate separates the concern so
> that only as many modules as necessary depend on that module.
>

Nope, how can't you see - that the dependency is equal in case you're
describing.

> This minimizes dependencies, which makes code change possible. The less
> dependency you have, the easier it is to change.
>

It doesn't minimizes as dependency is equal. But, yep it's true that
"The less dependency you have, the easier it is to change" - but it
doesn't related to the case.

> Modifying built-ins prototypes maximizes the dependency.

I've already described my meaning why augmenting of built-ins could be
the issue - only if:

(a) augmenting Object.ptototype till we haven't control of {DontEnum}/
[[Enumerable]]. This point goes without saying. But when we'll have
control of [[Enumerable]], I thinks it could be very useful.

(b) Using 3rd-party libs. But from this point of view - there's no
difference, where to describe your objects.

(c) If some, using some augmented built-ins, will have a habit to use
'string'.capitalize(), he can be confused not founding this method in
other project. But again - there's no difference which habit he has:
'string'.capitalize() or VeryOwnStringNamespace.capitalize() - there
will be no such method in other project. Or, maybe just psychological
difference - in case of 'string'.capitalize() user can think that it's
really own method - but, that's problem of the user - he first should
learn language on which he writes.

So - the dependency is equal.

> Everything has
> String.prototype, right?

Absolutely right.

> Well, now if you modify that, then everything
> has that modification.
>

Of cause not. "Everything" will have that modification when that
"everything" will *use* that modification. And there's no difference
between 'string'.capitalize() vs. VeryOwnStringNamespace.capitalize()
- dependency is equal.

>
> > 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.
>
> First off, who creates a namespace like "OutSuperDuperNamespace". Then,
> of those people, who then goes on to include *another* library that also
> the same (fruity) namespace?
>

The main idea (and understand that) is to show that you don't exactly
know what will some library provide "tomorrow". So your own "APE.dom"
may be overridden by all of that libs you'll use.

> A sensible developer would organize the coe into modules.

I know what modules are, be sure. `String.prototype' - is the kind of
a module itself. And if you are sure what you are doing, it's
absolutely not a bad practice to put `capitalize' into it.

> Obviously
> "DOM" (in any case) would be likely to conflict on global level. I use,
> for example, APE.dom.
>

That's good, but you understand that if you'll using dozen of 3rd-
party libs combined, your "APE.dom" theoretically can just gone in one
moment - when all the libs will provide the same names and structure.
Do you see the difference in this case from augmenting built-ins for
own goals (when you know and understand what are you doing)?

> And that way, there is no need to worr about a getPosition or getCoords,
> or getStyle function. I have the DOM module, which is all about the dom,
> then within that there are modules for style, position, events, and each
> aspect is organized so that it is pretty narrow, small and easy to test.
>
> That is modularity.
>

I know what modularity is. Why do you mention this? Do I say something
against modules? Or do I suggest do not use modules? But keep in mind,
that `String.prototype' - is the kind of a module itself.


>
> > 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).
>
> I'm not completely sure what that means.
>

That just means - that ideologically it's normal to augment built-ins
if language is constructed so and if this fact is in it's ideology.

So, I don't propagate everyone to augment built-ins (I think you think
so about my position, so I'm telling you - nope). My position is to be
fair for augmenting built-ins (which means, it against the categorical
statement "Augmenting built-ins - is a bad practice"). To augment or
not in this case - everyone choose - understanding all the issues.

/ds

John G Harris

unread,
Dec 30, 2009, 11:22:09 AM12/30/09
to
On Wed, 23 Dec 2009 at 19:39:41, in comp.lang.javascript, Dr J R
Stockton wrote:
>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.

Anyone who has set up their tab stops to view tables are not going to be
happy setting up 30 or so tabs to view a bit of javascript. Tabs are
convenient for writers but a nuisance for readers.

Two spaces are necessary and sufficient for the indent interval.

We are assuming, of course, that sensible people use a fixed-pitch font.
Anyone who uses a variable-pitch font deserves to be confused.


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

Very true.

John
--
John Harris

Asen Bozhilov

unread,
Dec 30, 2009, 8:48:48 PM12/30/09
to
Garrett Smith wrote:

> Host Objects:
>   * Operators:
>     - DO not use delete operator with host object (IE Errors)

That error can you see isn't only in IE. Try it code above in Firefox
3.5:

delete window.location; //Security error" code: "1000

Dr J R Stockton

unread,
Dec 30, 2009, 2:31:10 PM12/30/09
to
In comp.lang.javascript message <hhdit6$p43$1...@news.eternal-
september.org>, Tue, 29 Dec 2009 10:48:01, Garrett Smith
<dhtmlk...@gmail.com> posted:

>I added under DOM section:
>
>Host Objects:
> * Operators:
> - DO not use delete operator with host object (IE Errors)
> * Accessing Host objects that are or can be ActiveX objects.
>These may include, but are not limited to:
> - Disconnected nodes (node.offsetParent)
> - XMLHttpRequest methods
> - style filters
>
>ES5 requires all Host object to implement HasProperty, along with
>[[Get]], [[Delete]], [[DefaultValue]], et al (see Table 8). This is a
>big step in the right direction and I'm optimistic of more such things
>from the committee.

The type of person for which you ought to be writing will not understand
your jargon (host objects), and may be disconcerted by your lack of
grammar checking.

>> More suggestions for "Code Guidelines".
>> Doesn't have information:
>> - About `11.10 Binary Bitwise Operators` and how they converted
>> operands `ToInt32`. Which mean, with `Bitwise Operators` can loose
>> precision. See below:

Linguistic errors can be excused, even expected, from those with Russian
names; but must not be propagated. Spelling : "loose" -> "lose". And
"lose precision" means to get the answer approximately correct, with a
moderate number of LEAST significant bits wrong. Truncation to Int32
does not do that : rather than trim the toes, it decapitates.

>For numeric conversion, use unary + operator, for parsing numbers from
>strings, use parseInt(s, radix);

Whatever you mean, that does not express it comprehensibly.

Note that parseInt is not a universal nostrum; consider reading the
numeric part of a line known to be of the form "Mushrooms at $6.35/lb".
One uses a RegExp to separate the numeric part; unary + will convert the
matched part, but parseInt loses 35c.

--
(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)

Thomas 'PointedEars' Lahn

unread,
Dec 31, 2009, 2:30:46 PM12/31/09
to
kangax wrote:

Thanks, I stand corrected: As yet another deviation, the end tag of the TD
element (which is _not_ to be termed "the closing TD tag"!) may be omitted
in HTML 4.01 Strict, too (as specified by the `O' and the non-empty content-
model in the element declaration).


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)

Garrett Smith

unread,
Dec 31, 2009, 3:23:34 PM12/31/09
to

Given a piece of code M that has:-

String.prototype.capitalize = 1;

Another piece of code O that uses M now has capitalize method available.

<script src="m.js"></script>
<script src="o.js"></script>

So m.js creates a dependency from everything, to modification to
String.prototype.

If m.js were to define something else:-

M.capitalize= 1;

- then the exact same problem occurs. I think this is what you were
getting at.

>> Creating a separate file for string utils does not impose a global
>> change dependency.
>>
>
> Does. Absolutely the same. Take the example above - please count the
> changes you need - in *real* dependency - when some code *uses* that
> name: 'string'.capitalize() or VeryOwnStringNamespace.capitalize
> ('string').
>

A separate *file* would be depended on where it is included.

<script src="p.js"></script>
<script src="o.js"></script>

If p.js does not contain m.js (this could happen in a build), there
would be no dependency on M.capitalize.

If m.js is an author file (not using a build tool), is not about
built-in String/String.prototype, and is about formatting strings, then
m is defining two things:-
1) user defined string formatting
2) built in String

The user-defined String formatting routines could becomes properties of
one object, maybe stringFormat. That is clearly about one thing.

>> Putting the captilize function in a separate separates the concern so
>> that only as many modules as necessary depend on that module.
>>
>
> Nope, how can't you see - that the dependency is equal in case you're
> describing.
>

A module that adds a property to something it doesn't own introduces
something globally accessible that unrelated to the module itself. It is
doing more than it should. It is not really modular.

>> This minimizes dependencies, which makes code change possible. The less
>> dependency you have, the easier it is to change.
>>
>
> It doesn't minimizes as dependency is equal. But, yep it's true that
> "The less dependency you have, the easier it is to change" - but it
> doesn't related to the case.
>

A way to reduce change dependency would be to do less in each module.

>> Modifying built-ins prototypes maximizes the dependency.
>
> I've already described my meaning why augmenting of built-ins could be
> the issue - only if:
>
> (a) augmenting Object.ptototype till we haven't control of {DontEnum}/
> [[Enumerable]]. This point goes without saying. But when we'll have
> control of [[Enumerable]], I thinks it could be very useful.
>
> (b) Using 3rd-party libs. But from this point of view - there's no
> difference, where to describe your objects.
>

On this point, there is a huge difference where the object is defined.
If the client of the API defines String.prototype.capitalize, and the
library defines the same, there will be a conflict.

The library new version could define `YourCompanyNameSpace`, but why
would it?

> (c) If some, using some augmented built-ins, will have a habit to use
> 'string'.capitalize(), he can be confused not founding this method in
> other project. But again - there's no difference which habit he has:
> 'string'.capitalize() or VeryOwnStringNamespace.capitalize() - there
> will be no such method in other project. Or, maybe just psychological
> difference - in case of 'string'.capitalize() user can think that it's
> really own method - but, that's problem of the user - he first should
> learn language on which he writes.
>

On point (c), I see an issue with shared codebase; not necessarily
another project, per se, but elsewhere in the same application that is
using your module.

> So - the dependency is equal.

With either VeryOwnStringNamespace.capitalize, or
String.prototype.capitalize, yes, they both introduce globally
accessible method where they are included.

I want to look at Ext.util.Format.capitalize, then consider an
alterantive String.prototype.capitalize and compare alternatives. First
look at the Ext version.

First off, the package `Ext.util.Format` is not specific. Is `Format` a
verb or a noun? `Format` as a noun would seem to be a constructor, so
it shouldn't be that. If Format is a verb, then is it a method? What
does `Format` format? Does it format HTML code? Dates? Numbers?
Templates? As lengthy as that namespace is, it does not describe string
formatting. Indeed, format seems in the verb sense here, but it is not a
method; it is an object. The object has methods that perform many types
of formatting. None of the methods have much to do with each other;
they're categorized to work with strings and return strings. Instead, I
would prefer to shorten that to have just:-

Ext.formatString
Ext.formatHTML
Ext.formatDate

I've reformatted `Ext.util.Format.capitalize` function to wrap:

capitalize : function(value){
return !value ? value : value.charAt(0).toUpperCase() +
value.substr(1).toLowerCase();
}

There are a few problems with that function. When passed a falsish
value, the value itself is returned.

The non-standard substr method should be replaced with a call to the
standard String.prototype.substring.

The method does not consider strings that begin with non-characters,
such as leading whitespace or tic marks. For example, If input is "
higiri" and it is desired to have the method return the first
non-whitespace to upper-case, so " Higiri".

Here's a prototype'd version of Ext-js's "Ext.util.Format.capitalize":

if(!String.prototype.capitalize) { // Should we add a safety check?
return this.charAt(0).toUpperCase() + this.substr(1).toLowerCase();
}

Should there be a safety check? What if the safety check fails?

What about a piece of code that has access to the change to
String.prototype.capitalize, and wants to change it? Is that okay to
redefine String.prototype.capitalize? Is capitalization in a certain way
something that all strings should have, and should the method name be
`capitalize`?

Or what about:

String.prototype.startsWith?

What should that do?

If startsWith does something that is purely related to a *String*, and
not how *your application* is *using* strings, then it may be a good
candidate for a Standard in ES Harmony. For example,
String.prototype.trim that was added in ES5. Perhaps
String.prototype.startsWith could be a candidate for ES6.

If something is a good candidate for a Standard, then it is best to not
create a potential conflict. If ES6 defines String.prototype.startsWith,
but slightly differently, then the code that is defining
String.prototype.trim would want to avoid the safety check. It would
have to hide the built-in startsWith method and would want to avoid any
safety checks like:-

// No good if it is defined (in ES6, etc)
if(!String.prototype.startsWith) {

}

An alternative is the code could instead redefine
String.prototype.startsWith to String.prototype.myVeryOwnStartsWith.

But then we are getting to the point where the method name is trying
hard to have an identifier that identifies it as being something added
not built in.

>
>> Everything has
>> String.prototype, right?
>
> Absolutely right.
>
>> Well, now if you modify that, then everything
>> has that modification.
>>
>
> Of cause not. "Everything" will have that modification when that
> "everything" will *use* that modification. And there's no difference
> between 'string'.capitalize() vs. VeryOwnStringNamespace.capitalize()
> - dependency is equal.
>

By "use", I believe you mean to describe code that is accessing the
`capitalize` method, and not code that exists where the script that
defines `capitalize` exists.

Either way, I don't think it matters much. Once the API is published,
you don't get to decide who calls what. You can say: "I defined this
property, but don't use it," and if there is no value in using it, then
probably nobody will use it. If there is some value in using that
feature, then it has a better chance of being used. How would you know
who is using `capitalize`?

Either way, the method is globally accessible.

>>> 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.
>> First off, who creates a namespace like "OutSuperDuperNamespace". Then,
>> of those people, who then goes on to include *another* library that also
>> the same (fruity) namespace?
>>
>
> The main idea (and understand that) is to show that you don't exactly
> know what will some library provide "tomorrow". So your own "APE.dom"
> may be overridden by all of that libs you'll use.
>

I think we are arguing the same point.

That is, you don't know what may be defined tomorrow.

That public interface, is a property of global object, and so it could
be replaced by a simple assignment.

Anyone using that namespace could be expected to not redeclare that
namespace and to not use another piece of code that does.

YUI's YAHOO.namespace method fails on this account.

YAHOO.namespace fails because it adds user-defined properties to the
YAHOO object. Calling YAHOO.namespace("example") creates YAHOO.example,
if it does not exist alreay. YUI's namespace strategy makes it easy for
conflits to occur. Consider a client using YUI that wants to define
YAHOO.touchevent namespace. Will a future release of YUI have its own
YAHOO.touchevent object? YAHOO has no way to be certain that a client of
YAHOO had not followed YUI's advice and used
YAHOO.namespace("touchevent"). If YUI decides to use YAHOO.touchevent =
{}, then the namespace will be obliterated.

>> A sensible developer would organize the coe into modules.
>
> I know what modules are, be sure. `String.prototype' - is the kind of
> a module itself. And if you are sure what you are doing, it's
> absolutely not a bad practice to put `capitalize' into it.
>

String.prototype is a built-in. If it is to be called a "module", then
it is a built-in module. If you've modified it, then it is a built-in
module with a mix of user-defined properties.

If user-defined properties are defined, then where should these
definitions occur?

If the definition of user-defined additions to String.prototype is
defined in a author file that is defining another module, then the
author is defining two things in that file instead of one. So those
modifications should not occur in same author file as another module's code.

By "author file" I mean the file the author edits, not necessarily the
same file the http client receives.

The author file should be defining one thing only.

>> Obviously
>> "DOM" (in any case) would be likely to conflict on global level. I use,
>> for example, APE.dom.
>>
>
> That's good, but you understand that if you'll using dozen of 3rd-
> party libs combined, your "APE.dom" theoretically can just gone in one
> moment - when all the libs will provide the same names and structure.
> Do you see the difference in this case from augmenting built-ins for
> own goals (when you know and understand what are you doing)?
>

The only user-defined identifier that is ReadOnly is the Identfier for
FunctionExpression. And that doesn't work in JScript, as you probably know.

By that fact, you are are right; any one library can replace APE.dom.

A conflict can occur when *one* external module or library also modifies
the property String.prototype.capitalize.

The point is to not do that; to not modify objects you don't own.

Instead, I am suggesting that methods exist as part of units or modules
and with an easily identifiable role.

This can be achieved by defining one global namespace and hanging
properties off that.

If it is OK to modify String.prototype, is it okay for everyone to do
that, or just an internal organization?

Is it ok to modify objects you don't own in general? If so, are there
exceptions to that rule?

[...]

>
>>> 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).
>> I'm not completely sure what that means.
>>
>
> That just means - that ideologically it's normal to augment built-ins
> if language is constructed so and if this fact is in it's ideology.
>

The language allowing something does not make that thing ideal. The
language makes assignment to identifier end up with globals. How many
times have you seen a missing - var - statement.

for(i - 0; i < 10; i++)

?

One useful way to modify built-ins is to add the standard feature for
implementations that have not yet implemented it, or have implemented it
wrong, but preceeding that with a feature test, e.g.
if(!String.prototype.trim) ... .

If the rule "don't modify objects you don't own", is followed, and the
only exception to that rule is to add a global property, then conflicts
should not occur.

> So, I don't propagate everyone to augment built-ins (I think you think
> so about my position, so I'm telling you - nope). My position is to be
> fair for augmenting built-ins (which means, it against the categorical
> statement "Augmenting built-ins - is a bad practice"). To augment or
> not in this case - everyone choose - understanding all the issues.
>

I got that. I don't see a good reason for modifying objects you don't
own. I see a few downsides:-
1) increases potential conflict with
* new standard
* new version of 3rd party library
* code defined somewhere else in the organization

2) Method presence doesn't provide indication where that method is
likely to be defined.

Dr J R Stockton

unread,
Dec 31, 2009, 6:42:02 PM12/31/09
to
In comp.lang.javascript message <xtlkCULx...@J.A830F0FF37FB96852AD0
8924D9443D28E23ED5CD>, Wed, 30 Dec 2009 16:22:09, John G Harris

<jo...@nospam.demon.co.uk> posted:
>On Wed, 23 Dec 2009 at 19:39:41, in comp.lang.javascript, Dr J R
>Stockton wrote:
>>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.
>
>Anyone who has set up their tab stops to view tables are not going to be
>happy setting up 30 or so tabs to view a bit of javascript. Tabs are
>convenient for writers but a nuisance for readers.
>
>Two spaces are necessary and sufficient for the indent interval.
>
>We are assuming, of course, that sensible people use a fixed-pitch font.
>Anyone who uses a variable-pitch font deserves to be confused.

I think that you need to read what I wrote more slowly.

The proportion of people whose Web browsers and/or newsreaders are
routinely set up to have tab stops at other than 8N+1 must be
negligible.

Remember :
the most important reader must be the writer,
the code as written is not necessarily the code as transmitted.

Thomas 'PointedEars' Lahn

unread,
Dec 31, 2009, 8:14:47 PM12/31/09
to
Dr J R Stockton wrote:

> the most important reader must be the writer,

Utter nonsense.

> the code as written is not necessarily the code as transmitted.

Non sequitur.


PointedEars
--
Use any version of Microsoft Frontpage to create your site.
(This won't prevent people from viewing your source, but no one
will want to steal it.)
-- from <http://www.vortex-webdesign.com/help/hidesource.htm> (404-comp.)

Garrett Smith

unread,
Jan 1, 2010, 3:30:12 AM1/1/10
to

OK, but Firefox, or Gecko implement that as a native JSObject with
Object.prototype on the prototype chain. It is a little different in IE,
where the object is not a JScript object.

location.valueOf(); // Error in IE.

location instanceof Object; // False in IE

Dmitry A. Soshnikov

unread,
Jan 1, 2010, 12:43:01 PM1/1/10
to
On Dec 31 2009, 11:23 pm, Garrett Smith <dhtmlkitc...@gmail.com>

Yep.

> >> Creating a separate file for string utils does not impose a global
> >> change dependency.
>
> > Does. Absolutely the same. Take the example above - please count the
> > changes you need - in *real* dependency - when some code *uses* that
> > name: 'string'.capitalize() or VeryOwnStringNamespace.capitalize
> > ('string').
>
> A separate *file* would be depended on where it is included.
>
> <script src="p.js"></script>
> <script src="o.js"></script>
>
> If p.js does not contain m.js (this could happen in a build), there
> would be no dependency on M.capitalize.
>
> If m.js is an author file (not using a build tool), is not about
> built-in String/String.prototype, and is about formatting strings, then
> m is defining two things:-
> 1) user defined string formatting
> 2) built in String
>
> The user-defined String formatting routines could becomes properties of
> one object, maybe stringFormat. That is clearly about one thing.
>

Unclear. You correctly mentioned that "the exact same problem occurs"
with `String.prototype.capitalize' and `M.capitalize' in previous
part. Now you're talking about some "build tool" which builds
dependencies. What again difference do you see in that will "m.js"
contain `String.prototype.capitalize' or `M.capitalize', please
explain?

Let me again to mention the real dependency (regardless some "build
tools") - the dependency *is*, when some code uses that `.capitalize'
method, regardless how was it described.

If to take in mind you "build tool", I think augmenting of some built-
in object you'd like to put in some "global/general/built-in/common
-.js" which includes to *every* file. Meanwhile, "m.js" with own
namespace `M' and method `M.capitalize' will be included only in
needed files, right? Do I understand you correctly? Is this you want
to tell me? If so, let me again to mention about real dependency -
when code will *use* concrete and exact `.capitalize' method,
regardless *including* by some "build tool". Moreover, nothing
prevents to place `String.prototype.capitalize' also "m.js".

> >> Putting the captilize function in a separate separates the concern so
> >> that only as many modules as necessary depend on that module.
>
> > Nope, how can't you see - that the dependency is equal in case you're
> > describing.
>
> A module that adds a property to something it doesn't own introduces
> something globally accessible that unrelated to the module itself. It is
> doing more than it should. It is not really modular.
>

First, not exactly "globally". Second, it's not the module who puts
"something" into the "something". That *you* augment the built-in
module with new functionality to make more readable and useful code (I
remind, `String.prototype' is a module itself - so you put new
functionality into it. But not "some module is doing more than it
should").

> >> Modifying built-ins prototypes maximizes the dependency.
>
> > I've already described my meaning why augmenting of built-ins could be
> > the issue - only if:
>
> > (a) augmenting Object.ptototype till we haven't control of {DontEnum}/
> > [[Enumerable]]. This point goes without saying. But when we'll have
> > control of [[Enumerable]], I thinks it could be very useful.
>
> > (b) Using 3rd-party libs. But from this point of view - there's no
> > difference, where to describe your objects.
>
> On this point, there is a huge difference where the object is defined.
> If the client of the API defines String.prototype.capitalize, and the
> library defines the same, there will be a conflict.
>
> The library new version could define `YourCompanyNameSpace`, but why
> would it?
>

Not a huge - on practice, and equal on theory (why not for
`YourCompanyNameSpace`?). And again, that exactly users of a library
who will afraid and will not touch the `String.prototype' because they
think that they depend on library (and new version of library may do
everything). In other case users are independent from any library and
can augment everything they want, right? And that's not a bad practice
at all.

> > (c) If some, using some augmented built-ins, will have a habit to use
> > 'string'.capitalize(), he can be confused not founding this method in
> > other project. But again - there's no difference which habit he has:
> > 'string'.capitalize() or VeryOwnStringNamespace.capitalize() - there
> > will be no such method in other project. Or, maybe just psychological
> > difference - in case of 'string'.capitalize() user can think that it's
> > really own method - but, that's problem of the user - he first should
> > learn language on which he writes.
>
> On point (c), I see an issue with shared codebase; not necessarily
> another project, per se, but elsewhere in the same application that is
> using your module.
>

Yep, and it can be with any other own code shared anywhere, when some
will have a habit to use it. I mentioned that exactly to show that
there's no difference.

> > So - the dependency is equal.
>
> With either VeryOwnStringNamespace.capitalize, or
> String.prototype.capitalize, yes, they both introduce globally
> accessible method where they are included.
>

Yep.

Here you're describing something concrete and already regardless topic
(it's not so interesting how `capitalize' is implemented in ExtJS or
in Prototype.js, this method was taken only for an abstract example of
augmenting) - is it a good or bad practice to augment built-ins. So I
let myself to answer shortly - even regardless is a "good" or "bad"
candidate for "some next Standard", it's absolutely not a bad practice
from my point of view - if you understand what are you doing. That
will let to write more clear and useful code.

> >> Everything has
> >> String.prototype, right?
>
> > Absolutely right.
>
> >> Well, now if you modify that, then everything
> >> has that modification.
>
> > Of cause
>

> ...
>

Ok, I've "appreciated" this demagogy in this part of your answer ;)

So, concluding this ('cause I don't wanna to make a useless dispute -
I see what see, I know what I know), some questions I have to you:

1. Do you understand that your *statement* about augmentations of
built-ins - is just your own (humble) opinion? (Actually, exactly the
same as mine. But in difference from yours, mine doesn't forbid, but
explain why it's good and when it can be the issue).

Also, I'd like to mention, that firstly your statement sounded as
"Don't modify objects you don't own". There you didn't talk about
"built-ins" bug about abstract "not own" objects. Although, in our
talk I found out that you mean also built-ins. For me, touching some
*other* objects that I don't own (but not a built-ins) - is also can
be useless practice (although, I don't use words "bad practice",
'cause even regarding not to built-ins but to some other - it could be
useful to make some patch on some 3rd-party code, although, they can
do it themselves in new version of library).

2. I'd like to hear how exactly your position sounds. I've already
mentioned my position about this question: "I don't force anyone to
augment built-ins, I don't spread this idea, I'm just not agree with
the statement that augmenting of built-ins in dynamic language with
mutable objects - is a bad practice. Again - it's normal practice and
let to write more useful code against that long ugly as in ExtJS for
`.capitalize'".

So whatever you write (for whom this "Code Guidelines"?) - will you
write it or not (that it's a "bad practice") - I don't mind. But if
some using this "Code Guidelines" will (or will try to) judge anyone
by that question (about augmenting of built-ins) - I'll tell again,
that that people don't understand why they are judging so and they
don't think with their own head. Also that will be a bad practice of
using such "Code Guidelines" for *novices*, which will think that
everything written there (in statement manner!) - is conclusive true.
But it's not so.

P.S.: Happy New Year ;) Regards.

/ds

Dmitry A. Soshnikov

unread,
Jan 1, 2010, 12:53:20 PM1/1/10
to
On Jan 1, 8:43 pm, "Dmitry A. Soshnikov" <dmitry.soshni...@gmail.com>
wrote:

[snip]

>


> > >> Everything has
> > >> String.prototype, right?
>
> > > Absolutely right.
>
> > >> Well, now if you modify that, then everything
> > >> has that modification.
>
> > > Of cause
>
> > ...
>
> Ok, I've "appreciated" this demagogy in this part of your answer ;)
>

Sorry, Garrett I didn't see a half of your answer because of "read
more >>" link (I didn't see it before here), so I thought you write
only "Of cause and ...". I'll read the full your answer and will add
some answer to mine previous. It wasn't your demagogy in this place,
apologize.

/ds

Garrett Smith

unread,
Jan 1, 2010, 1:34:32 PM1/1/10
to
You're using Google Groups, then, I take it.

Dmitry A. Soshnikov

unread,
Jan 1, 2010, 2:06:01 PM1/1/10
to
On Dec 31 2009, 11:23 pm, Garrett Smith <dhtmlkitc...@gmail.com>
wrote:

[snip]

Continue to answer from this point (as I've mentioned, I didn't see
that half of your answer because of "read more >> " link).

>
> >> Everything has
> >> String.prototype, right?
>
> > Absolutely right.
>
> >> Well, now if you modify that, then everything
> >> has that modification.
>
> > Of cause not. "Everything" will have that modification when that
> > "everything" will *use* that modification. And there's no difference
> > between 'string'.capitalize() vs. VeryOwnStringNamespace.capitalize()
> > - dependency is equal.
>
> By "use", I believe you mean to describe code that is accessing the
> `capitalize` method, and not code that exists where the script that
> defines `capitalize` exists.
>

Yep, because (and I've already repeated not once) and
`String.prototype.capitalize' and `M.capitalize' can be defined in the
same exactly place (file) and used in the same exactly places.

> Either way, I don't think it matters much. Once the API is published,
> you don't get to decide who calls what. You can say: "I defined this
> property, but don't use it," and if there is no value in using it, then
> probably nobody will use it. If there is some value in using that
> feature, then it has a better chance of being used. How would you know
> who is using `capitalize`?
>
> Either way, the method is globally accessible.
>

Yeah, and that's exactly I'm talking about, when telling that there's
no difference.

> >>> 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.
> >> First off, who creates a namespace like "OutSuperDuperNamespace". Then,
> >> of those people, who then goes on to include *another* library that also
> >> the same (fruity) namespace?
>
> > The main idea (and understand that) is to show that you don't exactly
> > know what will some library provide "tomorrow". So your own "APE.dom"
> > may be overridden by all of that libs you'll use.
>
> I think we are arguing the same point.
>

Yeah, I see that too.

> That is, you don't know what may be defined tomorrow.
>
> That public interface, is a property of global object, and so it could
> be replaced by a simple assignment.
>
> Anyone using that namespace could be expected to not redeclare that
> namespace and to not use another piece of code that does.
>
> YUI's YAHOO.namespace method fails on this account.
>
> YAHOO.namespace fails because it adds user-defined properties to the
> YAHOO object. Calling YAHOO.namespace("example") creates YAHOO.example,
> if it does not exist alreay. YUI's namespace strategy makes it easy for
> conflits to occur. Consider a client using YUI that wants to define
> YAHOO.touchevent namespace. Will a future release of YUI have its own
> YAHOO.touchevent object? YAHOO has no way to be certain that a client of
> YAHOO had not followed YUI's advice and used
> YAHOO.namespace("touchevent"). If YUI decides to use YAHOO.touchevent =
> {}, then the namespace will be obliterated.
>

That's it.

> >> A sensible developer would organize the coe into modules.
>
> > I know what modules are, be sure. `String.prototype' - is the kind of
> > a module itself. And if you are sure what you are doing, it's
> > absolutely not a bad practice to put `capitalize' into it.
>
> String.prototype is a built-in. If it is to be called a "module", then
> it is a built-in module. If you've modified it, then it is a built-in
> module with a mix of user-defined properties.
>

Yeah, and I repeat, the main goal is about useful and elegant code
such as 'string'.capitalize() where `.capitalize' is put *logicaly*
there where it's place for it - in the strings "module/class". And
that's all about mostly when there's no some issues as 3rd-party libs
using.

> If user-defined properties are defined, then where should these
> definitions occur?
>
> If the definition of user-defined additions to String.prototype is
> defined in a author file that is defining another module, then the
> author is defining two things in that file instead of one. So those
> modifications should not occur in same author file as another module's code.
>
> By "author file" I mean the file the author edits, not necessarily the
> same file the http client receives.
>
> The author file should be defining one thing only.
>

I don't see a big issue. What's the prob - user can define
`String.prototype's extension in separate file - then will be "one
file for one thing", where "thing" is "patching built-in with useful
methods for to write more useful code instead of
Ext.util.Format.something".

> >> Obviously
> >> "DOM" (in any case) would be likely to conflict on global level. I use,
> >> for example, APE.dom.
>
> > That's good, but you understand that if you'll using dozen of 3rd-
> > party libs combined, your "APE.dom" theoretically can just gone in one
> > moment - when all the libs will provide the same names and structure.
> > Do you see the difference in this case from augmenting built-ins for
> > own goals (when you know and understand what are you doing)?
>
> The only user-defined identifier that is ReadOnly is the Identfier for
> FunctionExpression. And that doesn't work in JScript, as you probably know.
>

Yeah, thanks, be sure, I know (although, it's not about the topic).

> By that fact, you are are right; any one library can replace APE.dom.
>
> A conflict can occur when *one* external module or library also modifies
> the property String.prototype.capitalize.
>

Yes, sure. Have you noted that we're talking mostly about issues with
3rd-party libs? Meanwhile, we've put this fact into the issues when
augmenting can be the issue in case when some lib will do the same.
But what I'm talking about - is mostly regardless all mentioned issues
- that it's not a bad practice, when you understand why you do so.
This will help to write more useful and elegant code. But sure, when
to augment with using 3rd-party libs - that's already "for own fear
and risk".

> The point is to not do that; to not modify objects you don't own.
>
> Instead, I am suggesting that methods exist as part of units or modules
> and with an easily identifiable role.
>
> This can be achieved by defining one global namespace and hanging
> properties off that.

I understand that, and this structure is sure useful, but when
describing some methods that related to the strings - for what
additional module is needed? That "M" (and to write in one place
'string'.trim() and in other M.trimLeft(string))? For to know that
that's your extenstion but not a built-in? For do not make conflict
with the next Standard built-ins? Sure all of this clear, but when the
issue will be, then will find the solution. But for now we can write
more elegant and useful (and logically more correct in my opinion)
code such as 'string'.trimLeft().

>
> If it is OK to modify String.prototype, is it okay for everyone to do
> that, or just an internal organization?
>
> Is it ok to modify objects you don't own in general? If so, are there
> exceptions to that rule?
>

Good question. I think so: for exactly built-ins can be exceptions as
built-ins come from the beggining and every user (you or 3rd-library)
can do with them anything they want. So again, if you don't use some
3rd-party library, it can be useful to augment some built-in for to
write more useful and elegant code.

If you want to touch some object of 3rd-party (which you also can do -
to patch it) - you already do it for your own fear and risk. And here
can be useful to touch the properties which should appear in the next
releases (e.g. if you're using v.2 and know that in v.3 will be a
method doThat() - so you add your own implementations of doThat()). I
understand, that in case of built-ins can be exactly the same, but in
augmenting of both: built-ins or some 3rd-party library you may also
add your own patches regardless new versions - that which just useful
for you.

> [...]
>
>
>
> >>> 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).
> >> I'm not completely sure what that means.
>
> > That just means - that ideologically it's normal to augment built-ins
> > if language is constructed so and if this fact is in it's ideology.
>
> The language allowing something does not make that thing ideal. The
> language makes assignment to identifier end up with globals. How many
> times have you seen a missing - var - statement.
>
> for(i - 0; i < 10; i++)
>
> ?
>

Well, yeah, and that's why I've told repeatedly that user should
understand what he is doing. If he does, he can use the system in a
full power, if not - can catch every time errors such as example
above.

> One useful way to modify built-ins is to add the standard feature for
> implementations that have not yet implemented it, or have implemented it
> wrong, but preceeding that with a feature test, e.g.
> if(!String.prototype.trim) ... .
>

Yep, sure, I've told above about that. But also, you may add your own
additional functionality regardless new versions (maybe such
functionality which will never be added by Standard or by some lib).

> If the rule "don't modify objects you don't own", is followed, and the
> only exception to that rule is to add a global property, then conflicts
> should not occur.
>
> > So, I don't propagate everyone to augment built-ins (I think you think
> > so about my position, so I'm telling you - nope). My position is to be
> > fair for augmenting built-ins (which means, it against the categorical
> > statement "Augmenting built-ins - is a bad practice"). To augment or
> > not in this case - everyone choose - understanding all the issues.
>
> I got that. I don't see a good reason for modifying objects you don't
> own. I see a few downsides:-
> 1) increases potential conflict with
> * new standard
> * new version of 3rd party library
> * code defined somewhere else in the organization
>

Yep, I've told about the issues.

> 2) Method presence doesn't provide indication where that method is
> likely to be defined.

You mean if "M.foo.bar" means directory "M", subdirectory/file/module
"foo", method "bar" - you know where it is. And with
'string'.yourOwnMethod() you don't know where to search the definition
of the `yourOwnMethod'? I don't see that this a big issue. As variant
you can provide `built-ins-extensions.js' and do it there (or as
usually, some `core.js' or sort of and there sub routine for
initialize extensions of the built-ins).

So again, I'd like to say about my position: if do not touch all the
issues (main of which are: (a) Augmenting of the Object.prototype and
(b) using 3rd-party libs) - it can be useful in your own projects, and
you can write more clear, useful and elegant code (and that's all this
about, 'cause from functionality point of view, repeat, there's no any
difference where to put this code). But sure, if you do so with
regarding the described issues (especially using 3rd-party libs) - you
always do this for your own fear and risk.

/ds

Dmitry A. Soshnikov

unread,
Jan 1, 2010, 2:37:17 PM1/1/10
to

Yes I use Google Groups to see/answer. And what do you?

/ds

John G Harris

unread,
Jan 1, 2010, 3:17:56 PM1/1/10
to
On Thu, 31 Dec 2009 at 23:42:02, in comp.lang.javascript, Dr J R

The number of people using a browser or news reader to edit code is even
more negligible.


>Remember :
> the most important reader must be the writer,

No, the most important reader is the poor unfortunate who has the job of
updating or correcting the code, especially when they are not the
original author.


> the code as written is not necessarily the code as transmitted.

John
--
John Harris

Garrett Smith

unread,
Jan 1, 2010, 7:13:04 PM1/1/10
to
Dmitry A. Soshnikov wrote:
> On Dec 31 2009, 11:23 pm, Garrett Smith <dhtmlkitc...@gmail.com>
> wrote:
>> Dmitry A. Soshnikov wrote:
>>> On Dec 30, 4:04 am, Garrett Smith <dhtmlkitc...@gmail.com> wrote:
>>>> Dmitry A. Soshnikov wrote:
>>>>> 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.
[snip]

> Let me again to mention the real dependency (regardless some "build
> tools") - the dependency *is*, when some code uses that `.capitalize'
> method, regardless how was it described.
>
> If to take in mind you "build tool", I think augmenting of some built-
> in object you'd like to put in some "global/general/built-in/common
> -.js" which includes to *every* file. Meanwhile, "m.js" with own
> namespace `M' and method `M.capitalize' will be included only in
> needed files, right? Do I understand you correctly? Is this you want
> to tell me? If so, let me again to mention about real dependency -
> when code will *use* concrete and exact `.capitalize' method,
> regardless *including* by some "build tool". Moreover, nothing
> prevents to place `String.prototype.capitalize' also "m.js".
>
>>>> Putting the captilize function in a separate separates the concern so
>>>> that only as many modules as necessary depend on that module.
>>> Nope, how can't you see - that the dependency is equal in case you're
>>> describing.
>> A module that adds a property to something it doesn't own introduces
>> something globally accessible that unrelated to the module itself. It is
>> doing more than it should. It is not really modular.
>>
>
> First, not exactly "globally".

The thing that the module adds is globally accessible anywhere the
module is used.

Second, it's not the module who puts
> "something" into the "something". That *you* augment the built-in
> module with new functionality to make more readable and useful code (I
> remind, `String.prototype' is a module itself - so you put new
> functionality into it. But not "some module is doing more than it
> should").
>

I did not understand that.


[...]

>> // No good if it is defined (in ES6, etc)
>> if(!String.prototype.startsWith) {
>>
>> }
>>
>> An alternative is the code could instead redefine
>> String.prototype.startsWith to String.prototype.myVeryOwnStartsWith.
>>
>> But then we are getting to the point where the method name is trying
>> hard to have an identifier that identifies it as being something added
>> not built in.
>>
>>
>>
>
> Here you're describing something concrete and already regardless topic
> (it's not so interesting how `capitalize' is implemented in ExtJS or
> in Prototype.js, this method was taken only for an abstract example of
> augmenting) - is it a good or bad practice to augment built-ins. So I
> let myself to answer shortly - even regardless is a "good" or "bad"
> candidate for "some next Standard", it's absolutely not a bad practice
> from my point of view - if you understand what are you doing. That
> will let to write more clear and useful code.
>

The reason for looking at a concrete example was to look at why one
might modify String.prototype vs create own object.

Modifying String.prototype has some not so good consequences. They are:
(1) greater likelihood to conflict with something else than
YourOwn.stringFormat.capitalize. (a) future version of ES, (b) other
third party libs. (2) is less clear about where it is defined.

Does `captitalize` have to do with strings *in general*, or does it have
to do with the way your application *uses* strings? If so, then there is
greater likelihood of conflict with a future ES version. Otherwise, if
the method is *not* purely related to strings, then what is the
justification for adding it to String.prototype?

[...]

> So, concluding this ('cause I don't wanna to make a useless dispute -
> I see what see, I know what I know), some questions I have to you:
>
> 1. Do you understand that your *statement* about augmentations of
> built-ins - is just your own (humble) opinion? (Actually, exactly the
> same as mine. But in difference from yours, mine doesn't forbid, but
> explain why it's good and when it can be the issue).
>

I don't see design decisions as amtters of personal preference, if
that's what you mean. I see them as having consequences.

The consequences of modifying objects you don't own outweigh any
benefits to the coding style.

> Also, I'd like to mention, that firstly your statement sounded as
> "Don't modify objects you don't own". There you didn't talk about
> "built-ins" bug about abstract "not own" objects. Although, in our
> talk I found out that you mean also built-ins. For me, touching some
> *other* objects that I don't own (but not a built-ins) - is also can
> be useless practice (although, I don't use words "bad practice",
> 'cause even regarding not to built-ins but to some other - it could be
> useful to make some patch on some 3rd-party code, although, they can
> do it themselves in new version of library).
>

Are you suggesting to modify a 3rd party method by shadowing it with a
patch?

That sort of reverse inheritance creates a dependency cycle.

That can easily cause a problem where the "patch" causes a bug somewhere
else.

Format (other)
TableRenderer (own)

Lets say your TableRenderer depends on Format and Format.capitalize has
a problem, so you replace it it your code with:-

Format.capitalize = function() { /*...*/ };

And it works. Great so you patched it. Now it capitalizes those funny
german characters just as the German customers want, and it ignores some
wacky leading whitespace chars that somehow the user managed to paste
into the text input. Fixed it. Good.

Now for example, something else in Format, Format.captitalizeTrim
(whatever) depends on capitalize. TableRenderer doesn't care; that
captitalizeTrim code path never gets executed. When capitalizeTrim is
called, it gets *your* patch, but only when TableRenderer is present on
the page. When TableRenderer is not present, it does not get your patch.
Say now that captitalizeTrim has problems with your patch, perhaps only
occasionally.

TableRenderer has dependency in Format, Format has dependency within
TableRenderer.

That dependency cycle creates a problem.

Instead either:
a) create your own capitalize routine, but not replace the existing.
b) modify the source code directly and test it wherever it is being used.

Obviously (a) is much easier and smaller in scope, better for a hotfix,
but if the patch is safe and would fix (possibly hidden) bugs elsewhere,
then it makes sense to fix the bug.

You might also want to file a bug report, though don't expect an
immediate fix with third libraries. I have filed bugs over 1 year ago
that remain open. Of course I patched those bugs myself in the source code.

> 2. I'd like to hear how exactly your position sounds. I've already
> mentioned my position about this question: "I don't force anyone to
> augment built-ins, I don't spread this idea, I'm just not agree with
> the statement that augmenting of built-ins in dynamic language with
> mutable objects - is a bad practice. Again - it's normal practice and
> let to write more useful code against that long ugly as in ExtJS for
> `.capitalize'".
>

Are there any good reasons for modifying the built-ins?

> So whatever you write (for whom this "Code Guidelines"?) - will you
> write it or not (that it's a "bad practice") - I don't mind. But if
> some using this "Code Guidelines" will (or will try to) judge anyone
> by that question (about augmenting of built-ins) - I'll tell again,
> that that people don't understand why they are judging so and they
> don't think with their own head. Also that will be a bad practice of
> using such "Code Guidelines" for *novices*, which will think that
> everything written there (in statement manner!) - is conclusive true.
> But it's not so.
>

I'm writing the Code Guidelines for basis code reviews here.

An example of modifying not own objects that we saw recently was where
dojo adds a _listeners property to a function.

The next document is Code Review Guidelines. We are going to have good
code reviews here.

Garrett Smith

unread,
Jan 1, 2010, 7:22:29 PM1/1/10
to
Garrett Smith wrote:
> Dmitry A. Soshnikov wrote:
>> On Dec 31 2009, 11:23 pm, Garrett Smith <dhtmlkitc...@gmail.com>
>> wrote:
>>> Dmitry A. Soshnikov wrote:
>>>> On Dec 30, 4:04 am, Garrett Smith <dhtmlkitc...@gmail.com> wrote:
>>>>> Dmitry A. Soshnikov wrote:
>>>>>> 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.
> [snip]
>

[///]


>
> Are you suggesting to modify a 3rd party method by shadowing it with a
> patch?
>

Correction:

not "shadowning it with a patch" but
"replacing the value where needed".
[...]

Dmitry A. Soshnikov

unread,
Jan 3, 2010, 10:35:00 AM1/3/10
to
On 2 янв, 03:13, Garrett Smith <dhtmlkitc...@gmail.com> wrote:

[snip]
>


> Modifying String.prototype has some not so good consequences. They are:
> (1) greater likelihood to conflict with something else than
> YourOwn.stringFormat.capitalize. (a) future version of ES, (b) other
> third party libs. (2) is less clear about where it is defined.
>

Ok, let's conclude it. I completely understand that reasons (moreover,
with some of them I agree and mentioned myself).

What I was saying to you in this thread regarding to augmenting of
built-ins - is about *formulation* of the answer. Taking into account
that it's your article (or whatever it is) - you can write as you wish
including formulation such as "Don't touch/augment object that you
don't own".

Meanwhile, I suggested (and would write myself if it was my article)
something like this:

"Be careful augmenting/modifying objects that's you don't own.
Although, you can do this e.g. augmenting some built-ins (for getting
new needed functionality with more useful, logical and elegant code)
take in mind several well-known issues, main of which are: (a)
Augmenting Object.prototype because (here small explanation) and (b)
Using some 3rd-party libs (here again small explanations)."

Without saying is it a good or bad practice.

>
> Are there any good reasons for modifying the built-ins?
>

I've told, from functionality point of view - actually, there's no
difference where will you put this code. But the main reasons for me
to write 'string.capitalize()' instead of
YourOwnNamespace.SomeGreatModules.ThisInternalModule.ModuleForString.capitalize
() is:

- logical place for string's methods in string module (and I'll prefer
to put this functionality into the already existing module *taking
into account all issues I'll have (if I will));

- more useful and elegant code (in OOP-style instead of procedure-
style).

And please keep in mind, I'm not asking you may I write so or not,
'cause I repeat - I understand what I'm doing and why I'm doing so and
moreover, still repeat, that's just your own opinion with your own
issues (yeah, I understand that you'll always afraid that ES will (or
will not?) provide tomorrow (after several years) new method
`capitalize' in `String.prototype' and you understanding that will
use
YourOwnNamespace.SomeGreatModules.ThisInternalModule.ModuleForString.capitalize
() for that. Meanwhile me, understanding what that's all about and why
do I need this - will augment `String.prototype' with `capitalize' and
will use it. When after 5 years ES will provide the same method (and I
guess it will have similar functionality - just like with `trim' which
people use not the first year) - I'll use built-in method).

/ds

Jorge

unread,
Jan 3, 2010, 7:26:05 PM1/3/10
to
On Jan 3, 4:35 pm, "Dmitry A. Soshnikov" <dmitry.soshni...@gmail.com>
wrote:
> (...)

> And please keep in mind, I'm not asking you may I write so or not,
> 'cause I repeat - I understand what I'm doing and why I'm doing so and
> moreover, still repeat, that's just your own opinion with your own
> issues (yeah, I understand that you'll always afraid that ES will (or
> will not?) provide tomorrow (after several years) new method
> `capitalize' in `String.prototype' and  you understanding that will
> use
> YourOwnNamespace.SomeGreatModules.ThisInternalModule.ModuleForString.capita lize
> () for that. Meanwhile me, understanding what that's all about and why
> do I need this - will augment `String.prototype' with `capitalize' and
> will use it. When after 5 years ES will provide the same method (and I
> guess it will have similar functionality - just like with `trim' which
> people use not the first year) - I'll use built-in method).

There at least a couple of ways to avoid that situation :

1st.- Don't use a generic name such as "capitalize", use instead:
String.prototype.dmitrySoshnikovsCapitalize= function () { .. };

2nd.- Don't hard-code the name, do an indirection instead. For
example:
String.prototype[myApp.capitalize]= myApp.capitalizeFunction;

And then use "a string"[myApp.capitalize](); //Access indirectly.

3rd and best.- Get real. Forget about this until it actually becomes a
problem, if ever.
--
Jorge.

Garrett Smith

unread,
Jan 3, 2010, 11:01:03 PM1/3/10
to
Dmitry A. Soshnikov wrote:
> On Jan 1, 9:34 pm, Garrett Smith <dhtmlkitc...@gmail.com> wrote:
>> Dmitry A. Soshnikov wrote:
>>> On Jan 1, 8:43 pm, "Dmitry A. Soshnikov" <dmitry.soshni...@gmail.com>
>>> wrote:
>>> [snip]

[...]


>> You're using Google Groups, then, I take it.
>> --
>> Garrett
>> comp.lang.javascript FAQ:http://jibbering.com/faq/
>
> Yes I use Google Groups to see/answer. And what do you?
>

I use Thunderbird and eternal-september.org news server.

Garrett Smith

unread,
Jan 4, 2010, 12:26:03 AM1/4/10
to
Dmitry A. Soshnikov wrote:
> On 2 янв, 03:13, Garrett Smith <dhtmlkitc...@gmail.com> wrote:
>
> [snip]
>> Modifying String.prototype has some not so good consequences. They are:
>> (1) greater likelihood to conflict with something else than
>> YourOwn.stringFormat.capitalize. (a) future version of ES, (b) other
>> third party libs. (2) is less clear about where it is defined.
>>
>
> Ok, let's conclude it. I completely understand that reasons (moreover,
> with some of them I agree and mentioned myself).
>
> What I was saying to you in this thread regarding to augmenting of
> built-ins - is about *formulation* of the answer. Taking into account
> that it's your article (or whatever it is) - you can write as you wish
> including formulation such as "Don't touch/augment object that you
> don't own".
>

I am writing a Code Guidelines document. It is important for that
contents to be accurate and relevant.

> Meanwhile, I suggested (and would write myself if it was my article)
> something like this:
>
> "Be careful augmenting/modifying objects that's you don't own.
> Although, you can do this e.g. augmenting some built-ins (for getting
> new needed functionality with more useful, logical and elegant code)
> take in mind several well-known issues, main of which are: (a)
> Augmenting Object.prototype because (here small explanation) and (b)
> Using some 3rd-party libs (here again small explanations)."
>
> Without saying is it a good or bad practice.
>

The Code Guidelines document is for code reviews.

Design advice for code reviews might want to provide an alternative
suggestion and explain consequences for the design.

>> Are there any good reasons for modifying the built-ins?
>>
>
> I've told, from functionality point of view - actually, there's no
> difference where will you put this code. But the main reasons for me
> to write 'string.capitalize()' instead of
> YourOwnNamespace.SomeGreatModules.ThisInternalModule.ModuleForString.capitalize
> () is:
>

DOn't you think you're exaggerating the namespace typing issue just a
*little*?

Not even Qooxdoo and Ext have such long namespaces.

[...]

> - more useful and elegant code (in OOP-style instead of procedure-
> style).
>

How is it more "OOP" than defining a separate method on your own namespace?

[...]

> use
> YourOwnNamespace.SomeGreatModules.ThisInternalModule.ModuleForString.capitalize
> () for that. Meanwhile me, understanding what that's all about and why
> do I need this - will augment `String.prototype' with `capitalize' and
> will use it. When after 5 years ES will provide the same method (and I
> guess it will have similar functionality - just like with `trim' which
> people use not the first year) - I'll use built-in method).
>

Is the `captitalize` method related directly to strings, or is it about
formatting? Are there other types of formatting routines that may be
used in conjunction with that?

Dmitry A. Soshnikov

unread,
Jan 5, 2010, 5:11:32 AM1/5/10
to
On 4 янв, 03:26, Jorge <jo...@jorgechamorro.com> wrote:
> On Jan 3, 4:35 pm, "Dmitry A. Soshnikov" <dmitry.soshni...@gmail.com>
> wrote:
>
> > (...)
> > And please keep in mind, I'm not asking you may I write so or not,
> > 'cause I repeat - I understand what I'm doing and why I'm doing so and
> > moreover, still repeat, that's just your own opinion with your own
> > issues (yeah, I understand that you'll always afraid that ES will (or
> > will not?) provide tomorrow (after several years) new method
> > `capitalize' in `String.prototype' and  you understanding that will
> > use
> > YourOwnNamespace.SomeGreatModules.ThisInternalModule.ModuleForString.capita lize
> > () for that. Meanwhile me, understanding what that's all about and why
> > do I need this - will augment `String.prototype' with `capitalize' and
> > will use it. When after 5 years ES will provide the same method (and I
> > guess it will have similar functionality - just like with `trim' which
> > people use not the first year) - I'll use built-in method).
>
> There at least a couple of ways to avoid that situation :
>

> 1st.- Don't use a generic name such as "capitalize", use instead:
> String.prototype.dmitrySoshnikovsCapitalize= function () { .. };
>

Yeah, funny ;)

> 2nd.- Don't hard-code the name, do an indirection instead. For
> example:
> String.prototype[myApp.capitalize]= myApp.capitalizeFunction;
>
> And then use "a string"[myApp.capitalize](); //Access indirectly.
>

Yep, the sickness which is called "softcode" - when some afraid of
hardcode and see hardcode everywhere. Also funny, I don't wanna
support such code :)

> 3rd and best.- Get real. Forget about this until it actually becomes a
> problem, if ever.
>

Yep, I think so too.

P.S.: You forgot the 4th -
YourOwnNamespace.SomeGreatModules.ThisInternalModule.ModuleForString.capita
lize() :) Let's fill the code with that long lines and give for
supporting to somebody, he will be glad ;)

/ds

Dmitry A. Soshnikov

unread,
Jan 5, 2010, 6:01:40 AM1/5/10
to
On 4 янв, 08:26, Garrett Smith <dhtmlkitc...@gmail.com> wrote:

[snip]

>


> I am writing a Code Guidelines document. It is important for that
> contents to be accurate and relevant.
>

Yeah, right, but fully accurate can be only exact info such as e.g.
info from Standard or sort of. Info based on own opinion cannot be the
only one accurate and relevant. As I told, yours and mine - both are
own opinion with understandable issues; and I showed you the
difference of your and my opinions. So, you can choose yourself what
will you write in Code Guidelines document. The only thing I mentioned
- if this will be the document of judging - no one can judge anyone by
this question by that's own opinion, 'cause I'll be against again.
Against the formulation.

> Is the `captitalize` method related directly to strings, or is it about
> formatting? Are there other types of formatting routines that may be
> used in conjunction with that?
>

All the answers on such questions you can find yourself by the
situation and decide what to do.

Regards.

/ds

Thomas 'PointedEars' Lahn

unread,
Jan 5, 2010, 6:23:25 AM1/5/10
to
Garrett Smith wrote:

> Asen Bozhilov wrote:
>> Garrett Smith wrote:
>>> Host Objects:
>>> * Operators:
>>> - DO not use delete operator with host object (IE Errors)
>>
>> That error can you see isn't only in IE. Try it code above in Firefox
>> 3.5:
>>
>> delete window.location; //Security error" code: "1000
>
> OK, but Firefox, or Gecko implement that as a native JSObject with

How can you possibly know?

> Object.prototype on the prototype chain.

A host object may have a native object in its scope chain. That does not
make it a native object.

> It is a little different in IE,
> where the object is not a JScript object.
>
> location.valueOf(); // Error in IE.
>
> location instanceof Object; // False in IE

AISB, that is not a viable test.


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>

Jorge

unread,
Jan 5, 2010, 10:41:23 AM1/5/10
to
On Jan 5, 11:11 am, "Dmitry A. Soshnikov" <dmitry.soshni...@gmail.com>
wrote:
> (...)

> P.S.: You forgot the 4th -
> YourOwnNamespace.SomeGreatModules.ThisInternalModule.ModuleForString.capita
> lize() :)

But that's what you called the "procedural" flavor, and I prefer the
"OOP" flavor (inherited, by extension of the prototype).

> Let's fill the code with that long lines and give for
> supporting to somebody, he will be glad ;)

I read somewhere that one of Crockford's new years' resolutions was to
quit using single letter vars... :-)
--
Jorge.

Garrett Smith

unread,
Jan 5, 2010, 1:51:47 PM1/5/10
to
Dmitry A. Soshnikov wrote:
> On 4 янв, 08:26, Garrett Smith <dhtmlkitc...@gmail.com> wrote:
>
> [snip]
>
>> I am writing a Code Guidelines document. It is important for that
>> contents to be accurate and relevant.
>>
>
> Yeah, right, but fully accurate can be only exact info such as e.g.
> info from Standard or sort of. Info based on own opinion cannot be the
> only one accurate and relevant. As I told, yours and mine - both are
> own opinion with understandable issues; and I showed you the
> difference of your and my opinions. So, you can choose yourself what
> will you write in Code Guidelines document. The only thing I mentioned
> - if this will be the document of judging - no one can judge anyone by
> this question by that's own opinion, 'cause I'll be against again.
> Against the formulation.
>

Decisions of design are not merely matters of personal opinion or fancy.
Design decisions have consequences.

Design decisions based on the author thinking that the design is "cool"
often, and in this case, miss the consequences of those decisions.

The consequences shown:

1) More likely to conflict with:
a) code added by another contributor
b) a third party library
c) future ECMAScript specification/proposal

2) Not as clear as to who owns that functionality or where the
functionality is defined ("where is this method coming from?").

It is also possible to create a dependency cycle. It is possible that
the modification makes what should be internal information accessible to
other code (e.g. adding a _listeners property to functions).

>> Is the `captitalize` method related directly to strings, or is it about
>> formatting? Are there other types of formatting routines that may be
>> used in conjunction with that?
>>
>
> All the answers on such questions you can find yourself by the
> situation and decide what to do.
>

If you're not willing to provide evidence for your case for why
`capitalize` is preferable here, then there aren't any benefits to that.

The only benefits you provided are that you like it.

Dmitry A. Soshnikov

unread,
Jan 5, 2010, 4:56:12 PM1/5/10
to
On 5 янв, 21:51, Garrett Smith <dhtmlkitc...@gmail.com> wrote:

> Decisions of design are not merely matters of personal opinion or fancy.

Your should first tell it to yourself ;)

> Design decisions have consequences.
>
> Design decisions based on the author thinking that the design is "cool"
> often, and in this case, miss the consequences of those decisions.
>

Listen, ECMAScript is designed to be dynamic and mutable. Why are you
continue to propagate the static-language features just like you're
the only one who is judging here? I repeat, I don't ask you and don't
justify why can I do so (and will if it will be needed).

So about "cool", please, don't use such arguments. If you have another
opinion, which is based on your programing fear, you can easily
continue to write programs in your own design. That absolutely doesn't
mean that you're right in the only one way.

> The consequences shown:
>
> 1) More likely to conflict with:
>    a) code added by another contributor
>    b) a third party library
>    c) future ECMAScript specification/proposal
>
> 2) Not as clear as to  who owns that functionality or where the
> functionality is defined ("where is this method coming from?").
>
> It is also possible to create a dependency cycle. It is possible that
> the modification makes what should be internal information accessible to
> other code (e.g. adding a _listeners property to functions).
>

If there's no such consequences (should I repeat again, that I
understand all the issues?), why some should think that he's write
programs in "wrong" design? That's only your opinion. Only. Will you
mind?

And that's question with dependencies - you still continue to spread
some "dependency" which you think out yourself. Should I repeat/show
again, that dependency is equal?

> > All the answers on such questions you can find yourself by the
> > situation and decide what to do.
>
> If you're not willing to provide evidence for your case for why
> `capitalize` is preferable here, then there aren't any benefits to that.
>

You again started to use demagogy ("you not willing"). It's possible
to ask you to give answers *to me* (please pay attention in which
style of dialog we'll talk) about all the other (built-in) methods. I
also can continue just thinking out newer and newer reasons and
justifies about position which I've choose, but I sure won't, 'cause
there's no any reason to do so, I'm interested only in truth.

And the truth here is: that's only your own (and I'm underlying -
_humble_) opinion about programing on ECMAScript. Why have you decided
that you can judgjing me and think that it's you who will choose what
is correct and what is not? I'm telling you, in my opinion that long
crap such is Ext.util.Format.capitalize(string) - is really crap of ES
programing. What's hard to understand? Please ask, I can answer and
give explanations.

And again - about capitalize - it was just abstract name. Are you
unable to think abstractly? Don't touch concrete implementations,
meanings and so on, it's just superficially, tops, think more deeply -
about the subject and the theory but not about "what is capitalize"?
Ask yourself what is "trim" (regardless that in ES5 trim is generic)?
Just ask, and think why people use it with augmenting with
String.prototype? I use. And I like it, and I haven't any problem with
that, and I understand what I'm doing. What's wrong with me then from
your position? And, excuse me, who are you to tell me (to judge
me? ;)) that's something wrong with me in ES?

> The only benefits you provided are that you like it.

You can continue to use your system, but don't think that it's the
only one correct system. It's just the one opinion which can turn out
into the crap when you'll have some deep structure and will be forced
to write
YourOwnNamespace.SomeGreatModules.ThisInternalModule.ModuleForString.capitalize
() ;)

Sure I like and prefer use logical and useful string.capitalize(); You
can choose your own way and write the code which I really don't like
(I'm again about Ext.util.Format.capitalize(string)).

So, please write as you wish. When some then will judge somebody using
this document, I'll tell that author of document and the person who
will judge just understand ES from their own position (or even maybe
don't completely understand).

/ds

Garrett Smith

unread,
Jan 5, 2010, 6:39:43 PM1/5/10
to
Dmitry A. Soshnikov wrote:
> On 5 янв, 21:51, Garrett Smith <dhtmlkitc...@gmail.com> wrote:
>
>> Decisions of design are not merely matters of personal opinion or fancy.
>
> Your should first tell it to yourself ;)
>

What?

>> Design decisions have consequences.
>>
>> Design decisions based on the author thinking that the design is "cool"
>> often, and in this case, miss the consequences of those decisions.
>>
>
> Listen, ECMAScript is designed to be dynamic and mutable. Why are you
> continue to propagate the static-language features just like you're
> the only one who is judging here? I repeat, I don't ask you and don't
> justify why can I do so (and will if it will be needed).
>

Where did I propagate static language features?

> So about "cool", please, don't use such arguments. If you have another
> opinion, which is based on your programing fear, you can easily
> continue to write programs in your own design. That absolutely doesn't
> mean that you're right in the only one way.
>

I do not have programming fear. The arguments I have presented are
pretty logical. You've not shown counter for those, here:


>> The consequences shown:
>>
>> 1) More likely to conflict with:
>> a) code added by another contributor
>> b) a third party library
>> c) future ECMAScript specification/proposal
>>
>> 2) Not as clear as to who owns that functionality or where the
>> functionality is defined ("where is this method coming from?").
>>
>> It is also possible to create a dependency cycle. It is possible that
>> the modification makes what should be internal information accessible to
>> other code (e.g. adding a _listeners property to functions).
>>
>
> If there's no such consequences (should I repeat again, that I
> understand all the issues?), why some should think that he's write
> programs in "wrong" design? That's only your opinion. Only. Will you
> mind?
>

The problems of a program modifying objects it doesn't own exists
regardless of my opinion. An example of that problem was just
demonstrated by `String.prototype.trim` throwing errors when used as
specified by ES5.

> And that's question with dependencies - you still continue to spread
> some "dependency" which you think out yourself. Should I repeat/show
> again, that dependency is equal?
>

The "dependency cycle" was explained in the earlier message, too.

>>> All the answers on such questions you can find yourself by the
>>> situation and decide what to do.
>> If you're not willing to provide evidence for your case for why
>> `capitalize` is preferable here, then there aren't any benefits to that.
>>
>
> You again started to use demagogy ("you not willing").

I asked to to show the problem and post your code but you won't; you
refuse and keep saying 'demagogy".

It's possible
> to ask you to give answers *to me* (please pay attention in which
> style of dialog we'll talk) about all the other (built-in) methods. I
> also can continue just thinking out newer and newer reasons and
> justifies about position which I've choose, but I sure won't, 'cause
> there's no any reason to do so, I'm interested only in truth.
>
> And the truth here is: that's only your own (and I'm underlying -
> _humble_) opinion about programing on ECMAScript. Why have you decided
> that you can judgjing me and think that it's you who will choose what
> is correct and what is not?

Design decisions are not a matter of absolute right and wrong. Design
decisions have consequences.

We've been over the pros and cons and so far, the only pro is that you
like being able to use `"foo".capitalize()`.

I'm telling you, in my opinion that long
> crap such is Ext.util.Format.capitalize(string) - is really crap of ES
> programing. What's hard to understand? Please ask, I can answer and
> give explanations.
>

The "it's crap" argument is hard to understand. AIUI, "it's crap" means
you don't like it, but that you instead prefer what you call "OOP".

> And again - about capitalize - it was just abstract name. Are you
> unable to think abstractly?

Well we're discussing abstractions here. Where do you find my arguments
to be incorrect? Or where are my failings in thinking abstractly?

Don't touch concrete implementations,
> meanings and so on, it's just superficially, tops, think more deeply -
> about the subject and the theory but not about "what is capitalize"?

The point of drawing out your example is to show the actual code of
something that you proposed as being the better solution.

> Ask yourself what is "trim" (regardless that in ES5 trim is generic)?
> Just ask, and think why people use it with augmenting with
> String.prototype? I use. And I like it, and I haven't any problem with
> that, and I understand what I'm doing. What's wrong with me then from
> your position? And, excuse me, who are you to tell me (to judge
> me? ;)) that's something wrong with me in ES?
>

For production code, for code which is, or may be integrated with public
API, for code that is intended to work in the next version of an
implementation, avoid modifying objects you don't own.

It is usually very easy to avoid modifying objects that you don't own.

In the case of String.prototype.capitalize, it is so easy that there
doesn't even have to be very severe consequences in doing that to make
avoiding it a serious consideration.

It is trivial to create your own capitalize routine, but not replace the
existing.

>> The only benefits you provided are that you like it.


>
> You can continue to use your system, but don't think that it's the
> only one correct system.

That's a little too general here. The "system" is "don't modify objects

you don't own".

There may be exception for having motivation to do that, but it is
certainly not provided for in whatever sparse example or argument
presented so far.

It's just the one opinion which can turn out
> into the crap when you'll have some deep structure and will be forced
> to write
> YourOwnNamespace.SomeGreatModules.ThisInternalModule.ModuleForString.capitalize
> () ;)
>
> Sure I like and prefer use logical and useful string.capitalize(); You
> can choose your own way and write the code which I really don't like
> (I'm again about Ext.util.Format.capitalize(string)).
>

In code review, code that modifies objects it does not own should be
mentioned. If design of code can be improved, I want someone to say so,
for my code, at least. I want to know what I did that was odd,
confusing, inflexible, complicated.

> So, please write as you wish. When some then will judge somebody using
> this document, I'll tell that author of document and the person who
> will judge just understand ES from their own position (or even maybe
> don't completely understand).
>

If you have an argument for why String.prototype.capitalize is a good
thing, I haven't understood that (because I can't understand what you
won't show).

Do you put that in a user-file "built-ins.js", "string-mods.js" or
"format.js". What is `capitalize being used for? The abstraction should
be closely related to the object it deals with. The abstraction might be
about how your application uses strings and not String in general.

Dmitry A. Soshnikov

unread,
Jan 6, 2010, 8:24:17 AM1/6/10
to
On 6 янв, 02:39, Garrett Smith <dhtmlkitc...@gmail.com> wrote:
> Dmitry A. Soshnikov wrote:
> > On 5 янв, 21:51, Garrett Smith <dhtmlkitc...@gmail.com> wrote:
>
> >> Decisions of design are not merely matters of personal opinion or fancy.
>
> > Your should first tell it to yourself ;)
>
> What?
>

What "what"? That your decision is also based on personal opinion. You
describe some well-known issues related to augmenting of built-ins and
think that such pattern (don touch them! – yeah with exclamation mark
at the end ;)) – is the only one which is related to the professional
programming in production on ECMAScript. But that's only one of some
patterns and this invariant pattern (don't touch!) – is exactly
invariant and inflexible. Meanwhile, me, understanding what I'm doing
and why – can use all features of the language I write with full
power.

> >> Design decisions have consequences.
>
> >> Design decisions based on the author thinking that the design is "cool"
> >> often, and in this case, miss the consequences of those decisions.
>
> > Listen, ECMAScript is designed to be dynamic and mutable. Why are you
> > continue to propagate the static-language features just like you're
> > the only one who is judging here? I repeat, I don't ask you and don't
> > justify why can I do so (and will if it will be needed).
>
> Where did I propagate static language features?
>

Indirectly as the way you've chosen, though, it's fully in ideology of
dynamic based languages. There're some special patterns for most
useful augmenting and so on – to use on full power the system (the
language) on which you write.

Although, you didn't propagate static features directly and can
augment dynamically own object.

> > So about "cool", please, don't use such arguments. If you have another
> > opinion, which is based on your programing fear, you can easily
> > continue to write programs in your own design. That absolutely doesn't
> > mean that you're right in the only one way.
>
> I do not have programming fear. The arguments I have presented are
> pretty logical. You've not shown counter for those, here:
>

For me discussion is not "argument-counter" – in such ways that's just
dispute without finding the truth (which is always should be the only
one), but desire to defend the position. I don't see the big sense in
such discussions, ‘cause as a basis the own understanding, own pattern
is taken by the "The standard" which is wrong. That's only opinion,
only one of the ways which can be used or not – by situation.

You found out for yourself some pattern which is based on some
understandable issues. You then wanna to collect some rules and use
such pattern thinking that now you are free from issues and problems.
But from the other hand, fixing "problems" on one side, you can create
them on the other side. Why some should write
"YourOwnNamespace.SomeGreatModules.ThisInternalModule.ModuleForString.capitalize
()" Ah? Just because you always want to use some the only one patterns
which is protected from all issues and which is the only way? What's
the price for that? Code which looks overheated, too much detailed.

>
> >> The consequences shown:
>
> >> 1) More likely to conflict with:
> >> a) code added by another contributor
> >> b) a third party library
> >> c) future ECMAScript specification/proposal
>
> >> 2) Not as clear as to who owns that functionality or where the
> >> functionality is defined ("where is this method coming from?").
>
> >> It is also possible to create a dependency cycle. It is possible that
> >> the modification makes what should be internal information accessible to
> >> other code (e.g. adding a _listeners property to functions).
>
> > If there's no such consequences (should I repeat again, that I
> > understand all the issues?), why some should think that he's write
> > programs in "wrong" design? That's only your opinion. Only. Will you
> > mind?
>
> The problems of a program modifying objects it doesn't own exists
> regardless of my opinion. An example of that problem was just
> demonstrated by `String.prototype.trim` throwing errors when used as
> specified by ES5.
>

What do you mean "when used as specified by ES5"? I've told you – when
I haven't ES5 implemented – I use own, when ES5 will provide it – I
easily switch to implementation of the ES5 and will use it. So, that's
just demagogy – for what uses `.trim.apply(someThing)" with own
implementation? Sure if I need the way using as specified by ES5, I'll
use ES5's implementation.

> > And that's question with dependencies - you still continue to spread
> > some "dependency" which you think out yourself. Should I repeat/show
> > again, that dependency is equal?
>
> The "dependency cycle" was explained in the earlier message, too.
>

Which is equal, right? ;) I've heard.

> >>> All the answers on such questions you can find yourself by the
> >>> situation and decide what to do.
> >> If you're not willing to provide evidence for your case for why
> >> `capitalize` is preferable here, then there aren't any benefits to that.
>
> > You again started to use demagogy ("you not willing").
>
> I asked to to show the problem and post your code but you won't; you
> refuse and keep saying 'demagogy".
>

What kind of "problem and code" are you talking about? I repeat, the
most essential thing – is theory and *approach* to that. And from this
point of view there could be several approaches which is best fit to
situation, but not think out inflexible pattern which is always should
be used writing that long lines.

> It's possible
>
> > to ask you to give answers *to me* (please pay attention in which
> > style of dialog we'll talk) about all the other (built-in) methods. I
> > also can continue just thinking out newer and newer reasons and
> > justifies about position which I've choose, but I sure won't, 'cause
> > there's no any reason to do so, I'm interested only in truth.
>
> > And the truth here is: that's only your own (and I'm underlying -
> > _humble_) opinion about programing on ECMAScript. Why have you decided
> > that you can judgjing me and think that it's you who will choose what
> > is correct and what is not?
>
> Design decisions are not a matter of absolute right and wrong. Design
> decisions have consequences.
>

Sure, and should I repeat that I completely understand all the issues?
Should I? That I know about 3rd-party libs, Object.prototype and so
on? What' the problem? If I know about that and if I understand what
I'm doing – for what reason should I write such "long crap" instead of
ideological and useful method call on object itself but not the long
"YourOwnNamespace.SomeGreatModules.ThisInternalModule.ModuleForString.capitalize
()"?

Just explain me why, taking into account that I completely understand
all the issues. And if know that there will be no such situation, for
what reason should I write by that inflexible invariant pattern which
you think out to program in enemy environment, where it is not known,
what libraries load, as why extend etc. - in general, uncontrollable
system, where you should afraid of everything and for that's aim think
out "cool" pattern which helps to avoid that (yeah, I understand that
the price is – not so ideological and useful code).

> We've been over the pros and cons and so far, the only pro is that you
> like being able to use `"foo".capitalize()`.
>
> I'm telling you, in my opinion that long
>
> > crap such is Ext.util.Format.capitalize(string) - is really crap of ES
> > programing. What's hard to understand? Please ask, I can answer and
> > give explanations.
>
> The "it's crap" argument is hard to understand. AIUI, "it's crap" means
> you don't like it, but that you instead prefer what you call "OOP".
>

You're using specially the most "strong" parts of my cites to show
that I use some non-logical arguments, right? You can stop trying to
do it, I've already appreciate it ;)

But I meant the following, then all the code is penetrated by lines
such as (I let my self copy-paste one line):

YourOwnNamespace.SomeGreatModules.ThisInternalModule.ModuleForString.capitalize
()
YourOwnNamespace.SomeGreatModules.ThisInternalModule.ModuleForString.capitalize
()
YourOwnNamespace.SomeGreatModules.ThisInternalModule.ModuleForString.capitalize
()
YourOwnNamespace.SomeGreatModules.ThisInternalModule.ModuleForString.capitalize
()
YourOwnNamespace.SomeGreatModules.ThisInternalModule.ModuleForString.capitalize
()
YourOwnNamespace.SomeGreatModules.ThisInternalModule.ModuleForString.capitalize
()
YourOwnNamespace.SomeGreatModules.ThisInternalModule.ModuleForString.capitalize
()
YourOwnNamespace.SomeGreatModules.ThisInternalModule.ModuleForString.capitalize
()

If
(YourOwnNamespace.SomeGreatModules.ThisInternalModule.ModuleForString.capitalize
&&
YourOwnNamespace.SomeGreatModules.ThisInternalModule.ModuleForString.capitalize
()) {

YourOwnNamespace.SomeGreatModules.ThisInternalModule.ModuleForString.capitalize
()
} else {

YourOwnNamespace.SomeGreatModules.ThisInternalModule.ModuleForString.capitaliz}

Of cause, it's can be in general with some other objects in the system
and this question can be not related to the augmenting the built-ins,
but I don't see any reason to do this with built-ins if I understand
and know the system which I program.

> > And again - about capitalize - it was just abstract name. Are you
> > unable to think abstractly?
>
> Well we're discussing abstractions here. Where do you find my arguments
> to be incorrect? Or where are my failings in thinking abstractly?
>

You can leave provocation questions, I don't mind on them. I didn't
say about "incorrect, failings in thinking". I asked mostly to think/
talk about the ideology and the theory. Sure we should show some on
practice, but the main goal – is approach independently the exact
practice examples such as with capitalize(). I repeat, that this name
has been chosen just for abstraction with real example in e.g. ExtJS,
no more, no less. And you continue: "what is capitalize? Why is? Where
is it? Why is it there? Who are they? Why?" – that's I was talking
about – that's concrete deep practice things in this dialog is not so
interesting and not so essential. The approach and ideology are
essential.

> Don't touch concrete implementations,
>
> > meanings and so on, it's just superficially, tops, think more deeply -
> > about the subject and the theory but not about "what is capitalize"?
>
> The point of drawing out your example is to show the actual code of
> something that you proposed as being the better solution.
>

I've already told.

> > Ask yourself what is "trim" (regardless that in ES5 trim is generic)?
> > Just ask, and think why people use it with augmenting with
> > String.prototype? I use. And I like it, and I haven't any problem with
> > that, and I understand what I'm doing. What's wrong with me then from
> > your position? And, excuse me, who are you to tell me (to judge
> > me? ;)) that's something wrong with me in ES?
>
> For production code, for code which is, or may be integrated with public
> API, for code that is intended to work in the next version of an
> implementation, avoid modifying objects you don't own.
>

For production professional code, I'll use the system on all power,
flexible by situation, depends on variants I have – as in code
(looking, ideology elegance), as in performance. You can choose your
own way.

> It is usually very easy to avoid modifying objects that you don't own.
>
> In the case of String.prototype.capitalize, it is so easy that there
> doesn't even have to be very severe consequences in doing that to make
> avoiding it a serious consideration.
>
> It is trivial to create your own capitalize routine, but not replace the
> existing.
>

Why should I replace existing? Do you hear what I'm talking about? I
know and understand what can be, understand all the issues. If I'll
see the issues (if I ever will) I choose the other flexible way
programming in ideology of the language on which I write. You can
choose your own invariant pattern which you think out based on well-
known issues.

What the problem do you see?

> In code review, code that modifies objects it does not own should be
> mentioned. If design of code can be improved, I want someone to say so,
> for my code, at least. I want to know what I did that was odd,
> confusing, inflexible, complicated.
>

If all are taken into account, shouldn't. Why should? Why some should
say me: "A-ha! You're modifying built-ins, your code is not
professional, your code is not for production! A-ha!" Why I don't
understand if I know why did I use so and by what reason.

> > So, please write as you wish. When some then will judge somebody using
> > this document, I'll tell that author of document and the person who
> > will judge just understand ES from their own position (or even maybe
> > don't completely understand).
>
> If you have an argument for why String.prototype.capitalize is a good
> thing, I haven't understood that (because I can't understand what you
> won't show).
>

Well, I just can suggest to continue trying to understand that the
system you use can be used on all power depends on situation and
taking into account all the well-known issues.

What's the problem? Did I say that I don't understand some of those
issues? Did I, please answer? Or maybe I really don't understand them?
Or maybe I propagate and spread that: "Augment built-ins everywhere
independent the exact case! I don't wanna listen about issues and I
don't understand them!" Did I, please answer?

I've told repeatedly that I completely understand what's the all about
and why can I choose this that way, that I'm not limited by some
invariant pattern which can protect from all the issues but with some
special price for that – code which seems to me to overheated and odd
for ECMAScript programming.

I see that you operate with terms "you just like it, but my arguments
are about concrete issues", right? What arguments? Didn't I see and
understand all that arguments, please answer? Didn't I tell you that I
see the prob in *formulation*? That your chosen pattern is just only
of some variants which can be also professional and exec in production
environment. That you haven't even rights to write "don't use/touch!"
So for that I suggested: "Be careful…" which is more fairly. Will you
mind?

/ds

It is loading more messages.
0 new messages