4 ms·
While I endorse the argument for coding for readability (all things being equal), I don't agree with his example. I find the && syntax in javascript completely
by jackfoxy 16y ago
While I endorse the argument for coding for readability (all things being equal), I don't agree with his example. I find the && syntax in javascript completely readable.
- WesleyJohnson 16y agoI find it readable if you're trying to test both sides of the && to be true -- if(foo() && bar()){ // do this } However, the way it's written in the article, the intent is to merely test foo() and then execute bar() if foo() returns true. Even though I'm familiar with &&, it took me a minute to understand this as well. I'd be eqaully annoyed seeing this in production code.
- scott_s 16y agoIt's a common idiom in many programming languages.
- JshWright 16y agoI'm with the GP on this one... Readable code is very important. Using the short-circuiting property of && doesn't decrease readability in most cases (unless someone isn't familiar with the language, or the concept of using short-circuiting for flow control).
- DrSprout 16y agoI've always found the Perl foo() or die(); idiom to be quite readable. And if you're familiar with that, this is a pretty straightforward extension.
- div 16y agoI agree. As long as the example idiom is something that's used consistently throughout the code it's all good. Even if you're new to the code and don't immediately get it, you will instantly recognize it the second and third time around.
- JeanPierre 16y agoThis is pretty straightforward and intuitive, so I agree with this reply. Maybe it's because of the equivalents in lisp (I tend to use lisp a lot): (if (foo) (bar)) equals to (and (foo) (bar))
- psyklic 16y agoI disagree -- it probably is not immediately understood by most programmers. The main flaw of the technique is that the author uses the '&&' not as a logical operator (the intuitive use) but as a conditional operator. '&&' is the 'Logical AND'. The statement "foo() && bar();" just doesn't make initial sense, because the logical result of the expression is thrown out. After thinking this, the programmer probably will realize that the functions are actually called to evaluate the expression. And then finally (hopefully) the programmer realizes that they are evaluated short-circuit. So, the code may be functional but it is not very readable.
- leokote 16y ago"the expression evaluates to true if both return True, but then why is the result thrown out" Actually, the result is not thrown out: the && operator produces the value of its first operand if the first operand is falsy, otherwise it produces the value of the second operand. For what it's worth, there's also a procedural reading of "foo() && bar()" along the lines of "fill out this form AND win a prize!".
- psyklic 16y agoI wrote 'thrown out' because the statement is "A && B;" -- the result is unused due to the terminating semicolon.