|
Prev: FAQ Topic - Why does 1+1 equal 11? or How do I convert a string to a number? (2008-05-06)
Next: customerisnotalwaysright.
From: Richard Cornford on 5 May 2008 19:26 Zack wrote: > Hi, > > Let's say you have this function named validate. validate looks > like this: > > function validate() { > return ($F("Email") != '' ? ($("Name").value = $F("Email")) : > false); > } > > (Using prototype.js. For those not familiar $() is like > getElementById and $F is like getElementById().value for form > elements) There's a lot happening on this 1 line so let's break > it down. > > If the value of element "Email" is not empty string, return the > result of setting value of element "Name" = the value of > element "Email", otherwise return false. > > This works exactly as I want it too, but is it OK? By OK I mean > good javascript style? There's something fishy smelling to me > about doing any sort of assignment in the expression part of > the conditional. There is an often expressed style opinion that code that produces side effects should not appear in the expressions of a conditional operation; that under those circumstances an - if/else - block would be more appropriate, and make the side effect easier to observe. The assignment to the 'Name' field probably qualifies as a side effect in this case. One branch of responses to this thread seems to suggest that the side-effect in the conditional expression was not as apparent as it should be. However, in any programming language it would be considered bad style to be disregarding a language usage convention that appears in the language's specification, and as Prototype.js disregards ECMA 262 (all versions)'s injunction against using the $ symbol as the first character in any Identifier that is not machine generated if you are using Prototype.js it is already too late to be worrying about 'good style'. <snip> > But it's just not as cool looking. ... Programming is an activity where producing 'cool looking code' is never going to be a reason for doing anything. If 'cool looking' is a side effect of doing the right thing then so be it, otherwise it is a mistake to be doing anything but the right thing. Richard. |