- Feature Articles
- CodeSOD
- Error'd
- Forums
-
Other Articles
- Random Article
- Other Series
- Alex's Soapbox
- Announcements
- Best of…
- Best of Email
- Best of the Sidebar
- Bring Your Own Code
- Coded Smorgasbord
- Mandatory Fun Day
- Off Topic
- Representative Line
- News Roundup
- Editor's Soapbox
- Software on the Rocks
- Souvenir Potpourri
- Sponsor Post
- Tales from the Interview
- The Daily WTF: Live
- Virtudyne
Admin
Where, exactly, is the WTF in the Perl example?
Admin
Well, I don't know Perl, but sendmail is returning a boolean depending on the success of the call. If it fails (returns false), the code then calls fail (it's in the same shortcut conditional expression) which sets a variable called $failed to false. Why not just check what sendmail is returning?
Cheers, Julian
Admin
(0 == DblSpread)
I've heard of some programmers (mostly coming from a VB background) who do this as a matter of practice, because if you type
(DblSpread == 0)
there's a slight chance you might accidentally type
(DblSpread = 0)
And introduce bugs that are extremely hard to find. If you accidentally type
(0 = DblSpread)
then compilers will complain about trying to assign a value to a constant. So they always put the constant on the left when doing a comparison. I don't necessarily like this syntax, but I can see why some people use it.
Duplicating the same comparison twice in an OR statement is a (mild) WTF, though.
Admin
<FONT face=Arial color=#000000 size=2>Not sure if the <FONT color=#0000ff size=3><FONT size=2>$isValid!='true'</FONT> </FONT>being in twice is a typo or the WTF, but the approach is sound. $isValid could have gotten into the stylesheet any number of ways--as the value of a node in the XML, as a parameter when the stylesheet was called, whatever. All you're doing is saying "Display this page as a valid/invalid page". Move along, no business logic to see here...</FONT>
Admin
There's nothing wrong with putting the constant as the LH argument in an == conditional statement, and it's most definitely not mostly for folks from a VB background. It's recommended in a few very good general programming books and it can indeed save your ass from a lot of hair pulling (which can be very painful).
I've wasted enough time debugging my own code where an intended == had been typed as = because of my long nails and unresponsive keyboard. Once you shake the habit of listing operands in the ordinary order, it's a time saver.
Admin
I'm not completely sure, but doesn't XSLT have some kind of if..then..else? The choose..when..otherwise is overkill for this job.
Admin
Huh?
If $isValid = 'true', then the element never gets a class attribute. Though, I suspect the "enabledDiv" CSS class is just setting the element to have its default properties ("color: black;"), which is why this was never caught. Not a major WTF, but still a WTF.
For the first case, they probably meant to put test="$isValid='true'", but there's a minor WTF if $isValid is empty (the parameter wasn't passed in, there's no such attribute in the current node). In that case, both of the xsl:when tests would evaluate to false. Better to use test="$isValid='true'" and test="not($isValid='true')".
Also, I think some angle brackets got lost when this was posted. The code as presented is definitely not well-formed.
Admin
There is an xsl:if, but unfortunately, there is no xsl:else. The only way to mimic the if/else statement in XSL is the choose/when/otherwise structure.
Admin
Sorry, I looked again, and the code in Alex's original post is fine. It just somehow got messed up in the quoting.
Admin
*Nods*. I'm sure that the WTF here is not the LH constant, but the duplicated expression. Judging by Alex's comment regarding the symmetry of equality operators, the code should probably read "if ((0 == foo) || (foo == 0))", not "(0 == foo)" twice. Well, both would be WTFs, but of a different nature.
Admin
Admin
Actually, your slam on VB'ers isn't kosher here. It's not a VB thing to do the (0 == DblSpread), that's an old C thing, and probably around for a lot longer than C. I guarantee that equality checks of that order are in most corporate coding standards documents.
Admin
Actually I wouldn't be too quick to write off stuff like this as a WTF:
Sometimes I'll do this intentionally when I want to try turn an 'if' into an 'always' and see what happens with a block of code. Of course, things get messy when you come back to it two months later and have no idea why you did it.
Admin
Sure, that would work too... probably something like
if (sendmail(%mail))
{
# print success message
} else
{ &fail; # or just $failed = 1
# print error message
}
but I actually think the code listed reads better: "sendmail mail or fail"
Later code might check the value of $failed as well.
So it seems this is another version of the "setting boolean flags" WTF of earlier this week. I don't consider this a WTF... a minor annoyance, if that.
Admin
Unless you're comparing booleans...
if (guest.likes("bacon") = salad.has("bacon")) // oops meant ==
{ give(guest, salad);
}
Suppose user.likes("bacon") returns a lvalue above...
Dropping == for = goes from
"Do you like bacon, sir?" to
"Guess what, you now like bacon!" (or not, depending on whether the salad has bacon)
Admin
if (var = 0) ...
Ps. if the quoting failed, blame telligent systems, home of quality forum software.
Admin
Many, but not all. PHP doesn't and that's what I use most of the time. IIRC there isn't necessarily consistency in the semantics of the assignment operation. In most cases I know of, the assignment operation's return value is the value that's assigned, which lets you do things like
while ( (f = fgets(whatever)) != EOF) { do stuff }
because (f = fgets(whatever)) evaluates to fgets(whatever)
but I think some systems actually return true or false, i.e. whether the assignment operation succeeded, which is true almost all the time. So you don't want to rely on that. :(
I try to put the constant on the left in my == statements because it's no less readable than the usual way and it's just a good defensive programming practice. Defensive programming is a Good Thing when it's not totally out of control and you triple check every little thing.
Admin
It's good to see the word gallimaufry hasn't fallen out of usage. Perhaps, Alex, you have a WTF for us that would need the word grandiloquent in the title?
Admin
I bet this has something to do with how the UI is set up; perhaps a button that performs an action and a checkbox next to it that says "reset case". The code probably looks something like this:
sub button_OnClick()
' do some VB crap bla bla bla
ResetCase(checkbox.IsChecked)
end sub
That way, the button's event script doesn't need an IF statement to see if the checkbox is checked or not. If that's the case, then it hits on one of my pet peeves -- mixing the UI logic with the business logic [:@]
Admin
There's a similar notion with string literals (as well as other objects) in Java....
a lot of times I'll see:
if ("foo".equals(x))
instead of
if (x.equals("foo"))
in the second example, you could get a NullPointerException if x happens to be null; to guard against NPE's, the second example is rewritten as: if (x != null && x.equals("foo"))
if ("foo".equals(x)) is simpler to write.
It looked funny to me the first couple of times I saw it, but so did using a method, equals(), to compare objects for value equality.
Admin
The PERL thing should be written as in any other language, if you insist on a temporary:
$success = sendmail;
if($success) {
...
Using the weird &fail syntax obfuscates the correlation between the value of $failed and the operation being performed, not least because function calls don't require parentheses.
Eric Casto's snippet, if it is C++, might actually make sense, because classes can override both boolean conversion and the not operator - in particular, the tribool class has a maybe value that would return false for both.
Admin
for what it's worth, gcc will moan about
if (x = y)
leading to the standard ObjC construct
if ((self = [super init])) { }
The nested braces turn the assignment into a boolean, basically, and get rid of the warning.
With a decent compiler and -Werror -Wall, you're pretty much set, and 0 == foo becomes a thing of the past
Simon
Admin
"if" but no "else?" WTF!
Admin
Sadly not everybody uses a compiled language.
As an aside, I'd like to have an optionally strongly-typed language that would give you all the advantages of loose typing (as in Perl, PHP, etc) with the added debugging ease afforded by strongly typed languages. For example everything could be loosely typed with implicit conversion of strings to numbers and such, except for those cases where you force a variable to have one type only, say with something like
<FONT face="Courier New">assert int $a = 0;</FONT>
If your program attempts to assign a non integer value to $a at any point (e.g. from a sql query with weird field to variable or array index mapping) the program would complain. You could extend that to objects with
<FONT face="Courier New">assert MyClass $obj;</FONT>
Then if you call a mysql_fetch_object and assign the result to $obj, and the structure of your db resultset isn't compatible with a MyClass object, the program would complain.
I can't count how many hours I've wasted debugging code just because a variable wasn't assigned what I expected it to be assigned but no error occurred because of a language's loose typing.
Admin
> (DblSpread == 0)
> there's a slight chance you might accidentally type
> (DblSpread = 0)
That's right. I've encountered this problem some time ago, while programming in both Pascal and C.
Just like The Last Bug:
while (1)
{
int status = getRadarStatus();
if (status = 1) launchNuclearMissiles();
}
Admin
I agree... A bit verbose, yet not really a WTF. It could have been:
But that's just a matter of style. The other way is perfectly fine.
dZ.
Admin
I beg to differ. Its only obfuscated to non-Perl weenies. In Perl, it is a matter of conventional style to use constructs of the form:
This is read as "do the deed or fail miserably", which follows a semantic approach to code style. Many features of the language have been adapted to maintain this style of legibility. Of course, to anybody not familiar with Perl, this may seem weird or unexpected, as it strays from the more "structured" and stricter syntax rules of other languages. But then again, anybody not familiar with Perl shouldn't be messing with that code anyway.
dZ.
Admin
Nevertheless, your post doesn't answer the crucial question of whether Larry Wall's wife is the mother of Perl.
Admin
Only Mr. Krabs knows for sure (SpongeBob reference)
Admin
Actually, this is reminiscent of how the main accounting software at my day job compensates for the lack of BEGIN TRANSACTION type functionality (it dates back to the 70s; there's a SQL option now, but it's spendy enough that most users don't bother). Example using pseudocode:
loop through all records
step_001:
if already did step 001 for this record then goto step_002
do step 001 for this record
record that I did step 001 for this record
step_002:
(etc.)
end loop
Of course, this is a WTF in itself for not using enough subroutines. They're moving a few modules at a time to OOP - the externals look clean, dunno about the internals though.
Admin
That should never happen in Pascal, since Pascal uses := for assignment and = for equality.
Admin
C/C++/C#/Java are also have different operators '=' for assignment and '==' for equality check. The problem is that C and C++ allow treatment of integer results to be interpreted as "boolean" (everything which is not a 0 is true). In C# and Java this problem doesn't exist because they were "cured" from this disease and allow only boolean expressions in the 'if' statement.
i.e.
int a;
if (a = GetStatus()) //is valid in C/C++ (usually generates a warning)
to make the same trick in Java/C# you must type more :)
if ((a = GetStatus()) != 0)
Pascal is more strict - it doesn't allow assignments inside if statement
i.e.
var a: Integer;
begin
a := GetStatus(); (* the is no way to make this assignment inside if*)
if a <> 0 then
Admin
Most of the time, I don't either. I spend most of my time in either Ruby or Smalltalk these days, although I do relish the time I spend in ObjC as well.
You don't unit test, do you? That's exactly the type of shite that unit testing picks up.
Simon
I truly, truly hate captcha
Admin
I mean after programming a lot in Pascal, I've made sometimes mistakes like using = instead of == in the first few days of returning to C.
Admin
You don' t have to use a compiled language to be warned when you accidentally assign instead of comparing. Take Ruby, for example:
Rik
Admin
as others have pointed out, there's nothing wrong per se with having UI rules inside XSLT. It is better that Alex does not criticise what he does not fully appreciate. The flaw is with the logic, not the use of conditionality to determine UI results.
Admin
This should at least USE the <otherwise> element that is there [I]
<xsl:choose>
<xsl:when test="$isValid='true'">
<xsl:attribute name="class">enabledDiv</xsl:attribute>
</xsl:when>
<xsl:otherwise >
<xsl:attribute name="class">disabledDiv</xsl:attribute>
</xsl:otherwise>
</xsl:choose>
enabledDiv and disabledDiv seem like generic names, maybe a $cssClassName would be a better variable to use.
You <FONT color=#0000ff>can assign it whereever it was that you set $isValid, then get rid of this additional condition and use.
<xsl:attribute name="class"><FONT color=#000000><xsl:value-of select="$cssClassName"></FONT></xsl:attribute>
</FONT>
<FONT color=#0000ff></FONT>
Admin
That's true, but mistakenly typing '=' instead of '==' is much more plausible than mistakenly typing ':=' instead of '='.
Admin
Note the useless use of & to call functions. It's typical for programmers who never learnt Perl properly. The &fail means that callee's arguments are aliased to caller's arguments, which could have interesting and fully unexpected consequences. The other form, &foo(), bypasses Perl prototypes which often results in function calls that don't quite do what they seem to do...
The code above is helpless abuse of Perl.
Admin
Try Flash Actionscript 2.0. It behaves like that. If you specify a type when declaring the variabel it'll do typechecking(unless you assign the value of an "untyped" variable). But if you exclude the typedeclaratin it can be assigned just about anything.
Admin
Unnecessary use of globals, tho.
Admin
True, but it's still a misuse of the idiom in question. The idiom assumes that the failure clause is a complete action itself, usually a call to an error-reporting function such as die() or croak(). Furthermore, the idiom assumes that there is no 'else' clause, or else an implicit one - it is most often used for reporting a <i>fatal</i> error and forcing an early exit of the program. Using it to set a variable which is immediately tested on the next line is pointless and would be a WTF even to someone familiar with the idiom (as I was).
In any case the actual WTF is that he is using a separate function to set a global variable, with no gain in abstraction, while handling the actual error logging inline.
Admin
Also, unneccesary messing with the stack if the box isn't checked.
Admin
The worst part is that the setting of the global variable happens only if sendmail failed.
$success = sendmail(%mail);
sets $success to the scalar return value of sendmail, unconditionally. This may have unintended side effects if $success is to be used elsewhere, but at least is correct locally. Otoh,
sendmail(%mail) || &fail;
sets the value of $failed only if sendmail returns 0. That is, if someone has already set $failed=1 long before these lines are called and sendmail returns 1, $failed will not be touched, and the error message will be very hard to debug.
One reason to follow Perl idioms very closely.
sendmail(%mail) || carp "Can't send mail";
simply doesn't have this problem.
Admin
Python does it smart -
http://www.python.org/doc/faq/general.html#why-can-t-i-use-an-assignment-in-an-expression
It just avoids the whole mess.
Admin
Erk - I mean
http://www.python.org/doc/faq/general.html#why-can-t-i-use-an-assignment-in-an-expression
Admin
Admin
Except in cases when it's more readable than the "conventional" order. Compare:
if (0 == someFunctionWithLongName (with, some + arguments (that, maybe, call), some, other (functions), and so (on) and so (on)) {
with:
if (someFunctionWithLongName (with, some + arguments (that, maybe, call), some, other (functions), and so (on) and so (on) == 0) {
In the second case you have to parse _whole_ statement to see what's compared with what.
I think readability is the most important criteria when you can write the relation either way. And the easier you can find operator the better readability.
Admin
Java does allow assignment inside the test, and if the assignment is a boolean, you don't need anything more eg:
boolean tempBool;
if (tempBool = methodThatReturnsABoolean()){
System.out.println("YES");
}else{
System.out.println("NO");
}
is perfectly legal.... but I really don't like it.
Admin
Interesting. Someone's invented complex booleans with a 'maybe' value? I wonder what the keyword and Number equivalent would be.
var foo = maybe and var foo = new ComplexBoolean(0.5) ?