From: Robert Klemme Date: 2004-06-13T04:43:37+09:00 Subject: Re: assignment in conditional warning "Ara.T.Howard" schrieb im Newsbeitrag news:Pine.LNX.4.60.0406120931350.3345@harp.ngdc.noaa.gov... > On Sat, 12 Jun 2004, Robert Klemme wrote: > > >> Most novice programmers would want to use that. > > > > I beg to differ: the *only* reasonable usage of assignment in conditionals > > is with "while" and "until", i.e. looping constructs, like in: > > > > while ( line = gets ) > > line.chomp! > > # do something with current line > > end > > > > Assignment in "if" and "unless" is totally superfluous. It obfuscates code > > and is not needed at all. Every "if ( x = expression )" can be converted to > > > > x = expression > > if x > > ... > > > > which is *much* clearer and cleaner IMHO. Alternatively you can do this in > > some cases: > > > > x = expression and puts "yes" > > IMHO the above fails apart when you are testing compound datastructures using > assignment to deconstruct the structure into more manageable peices in the > test. which is cleaner/clearer? > > 1) > > tuples = db.execute sql > > raise "something terrible has happened in the database" unless > (tuple = tuples.first) and (answer = tuple.first) and (answer == 42) > > 2) > > tuples = db.execute sql > > raise "something terrible has happened in the database" unless > tuples.first and tuples.first.first and tuples.first.first == 42 > > 3) > > tuples = db.execute sql > > tuple = tuples.first > answer = tuple.first > > raise "something terrible has happened in the database" unless > answer == 42 > > > > i can seem someone chosing 1 or 3 from above. but when the code size starts > to grow i think most programmers, given a choice between two clear statements, > chose the shorter one and that, in fact, the __length__ of a statement > relative to it's source file is directly related to it's understand-ability. > especially consider the case where the variables 'tuple' and 'answer' are not > used except for testing purposes - isn't it better to isolate them to the > conditional expression then? if course, you don't have to name them at all > (2), but that IS obfuscated! One of the three tests is superfluous. So it's rather tuples = db.execute sql raise "something terrible has happened in the database" unless tuples.first && tuples.first.first == 42 which doesn't look too bad IMHO. Regards robert