jastrachan | 7 Jul 18:26 2004
Picon

Re: using || and && in a more clever way


On 7 Jul 2004, at 16:47, John Wilson wrote:

>
> On 7 Jul 2004, at 16:10, Wilson, Greg wrote:
>
>>>> x ||= "foo"
>>
>>> John Wilson:
>>> However this begins to slide us in the Perl direction ;)
>>
>> Greg Wilson:
>> I use "x = a or b" a lot in Python (and equivalent forms in
>> C++ and Perl), but whenever I teach them, at least half the
>> class never really understands what's going on.
>>
>> Students seem to have less trouble with ternary ?:, until it
>> comes time to chain it.  They find:
>>
>>     x = a ? a : (b ? b : c)
>>
>> harder to invent/read/debug than:
>>
>>     x = a or b or c
>>
>
> yes I don't have an issue with the use of an operator it's overloading 
> the semantics I don't like:
>
> I want to do:
>
> if (!x) {
> 	x = y
> }
>
> I also want to do
>
> if (x == null) {
> 	x = y
> }
>
> I don't want to do
>
> if {x == null || !x) {
> 	x = y
> }

If you want to be specific you can be more explicit in your code. e.g.

if (x == false) {...}

or

if (x == null) {...}

to avoid the coersion to a boolean.

> at the moment '||' does the first thing, the proposed change makes it 
> do the third  thing.
>
> I can see me writing code which sets a variable to a default value if 
> it's null without realising that it will fail to do what I want if the 
> value I'm testing happens to be a non null Boolean with the value 
> false.

But || is normally used for logical operations; if the left hand side 
is false (or null) surely its not surprising to use the right hand 
value?

James
-------
http://radio.weblogs.com/0112098/


Gmane