Catch and Release

« Return to Article
  • Cyrus 2007-01-25 09:04
    I don't think they quite understand stack unwinding; though I'm interested to hear someone defend this, could be interesting.

    Captcha: Bling, word.
  • rmr 2007-01-25 09:07
    I especially like the fact that every email sent out will include %%FirstName%% and %%LastName%% because of the ToLower() call in the swtich.
  • Benanov (can't login) 2007-01-25 09:08
    It's completely useless! String.Replace(string1,string2) is s/string1/string2/g

    Captcha: ewww (how true)
  • pete 2007-01-25 09:13
    my great new list implementation:


    public static Exception obfuscateArray(String[] members)
    {
    Exception e = new Exception(Integer.valueOf(mebers.length));

    for(int i=0; i < members.length; i++)
    {
    try
    {
    throw new Exception(members[i], e);
    }
    catch(Exception x)
    {
    e = x;
    }
    }
    return e;
    }
  • ntheory 2007-01-25 09:16
    "mebers" causes an error. Oh well, guess I can't put that into production yet.
  • Mikkel Høgh 2007-01-25 09:16
    This is hilarious...
    Who said it wasn't possible to make a simple mater of string replacement impossibly complicated - even in C#.
  • shenme 2007-01-25 09:17
    Is there some reason you'd code '%' two different ways, Unicode "\u0025" or 'normal' "%" ?

    Is there some rule saying you couldn't just say "switch (match.Value.toLower())" and then 'case "%%username%%":' ?

    Does 'Body.Replace("%%password%%",' do case-insensitive matching, in case the instance was "%%pASSword%%" ?

    --
    I'm a pessimist about probabilities; I'm an optimist about possibilities.
    Lewis Mumford (1895-1990)
  • maratcolumn1 2007-01-25 09:17
    Like many of my managers liked to say, "Our program should never fail." Hence:
    try {
    
    anyOfMyFunctions();
    } catch (Exception e) {
    System.out.println("Exception!");
    }


    P.S. I'll kill you if you tell them about Throwable and Error.
  • Odhran 2007-01-25 09:22
    What a bloody awful piece of code!!

    They obviously never heard of XSL transforms either ... for shame!
  • XIU 2007-01-25 09:39
    shenme:
    Is there some reason you'd code '%' two different ways, Unicode "\u0025" or 'normal' "%" ?

    Is there some rule saying you couldn't just say "switch (match.Value.toLower())" and then 'case "%%username%%":' ?

    Does 'Body.Replace("%%password%%",' do case-insensitive matching, in case the instance was "%%pASSword%%" ?


    \u0025 and % is exactly the same. You could do case "%%username%%" but that's not really the point, string.Replace replaces everything it finds, so you could just call all the Replace things, no need for Regex either. And string.Replace is case-sensitive so it would leave "%%pASSword%%"

    And then returning the exception, this is just one big WTF.
  • gram 2007-01-25 09:42
    they also haven't heard about Regex.Replace, which makes life easier (:
    but it's true, xslt is the right way
  • Marcin 2007-01-25 09:46
    Consider: the use of exceptions will prevent the mail being sent, preventing erroneous behaviour.

    The caller might want to defer exception handling in order to do generic cleanup etc. that would otherwise have to be replicated in each handler. Java/C#/C++ exceptions do impose certain style costs in that regard, and the writer of this code might want to avoid that.
  • gram 2007-01-25 09:52
    if you want to defer exception handling, you just don't need to catch it here...
  • John Cowan 2007-01-25 09:53
    Sure, why not return an exception? It's a first-class object; you can pass it around however you like, pick it apart, whatever. Nothing says you *have* to throw it.
  • abx 2007-01-25 10:04
    If I were to call a method, and I noticed that the return type was an exception, I would consider sending the damn email myself.
  • Smudge 2007-01-25 10:06
    Whenever I see "== true" or "== false", it's always a guarantee that the rest of the code will be awful too. This one didn't disappoint,
  • Frzr 2007-01-25 10:18
    "Catch and Release is more than just a way of hurting fish for fun." -- Dogbert

    Captcha: atari, where you had no exceptions.
  • snoofle 2007-01-25 10:18
    Odhran:
    What a bloody awful piece of code!!

    They obviously never heard of XSL transforms either ... for shame!

    Yeah, because someone who would write something like this needs to be turned loose with XSLT...

    ... not saying XSLT is the wrong way, just this seems like the wrong person to attempt to use it!
  • willy 2007-01-25 10:27
    Smudge:
    Whenever I see "== true" or "== false", it's always a guarantee that the rest of the code will be awful too. This one didn't disappoint,


    I dunno, in any language I try to make things as explicit as possible. having '== true' or whatever (although a bit redundant makes it obvious as to what the return type is being evaluated in the conditional without the need to investigate further.

    I do a lot of code maintenance, so maybe it's just me, but when I'm skimming through existing code after its been written, little visual queues like this save time and brainpower.
  • Your Name 2007-01-25 10:28
    I agree with you on single comparisons, but when there are muliple ands and ors, it doesn't hurt to really say what you mean.

    I hope you aren't one of those people who also berates others for using excess parentheses, because they "slow down the compiler" or something.
  • AndrewB 2007-01-25 10:31
    Smudge:
    Whenever I see "== true" or "== false", it's always a guarantee that the rest of the code will be awful too. This one didn't disappoint,


    Ever heard of readability?
  • Fredric 2007-01-25 10:32
    I must say that I had never thought of returning an exception until now.

    It's quite a strange way of returning an error code, but essentially it's the same thing.

    With the difference that Null means the function succeeded, while usually if a function returns Null you'd expect it to have failed. In this case it fails if it actually returns something...

    And the lower/upper case stuff... That's just dumb...

    captcha: bathe, is that even a real word?
  • snoofle 2007-01-25 10:32
    Your Name:
    I agree with you on single comparisons, but when there are muliple ands and ors, it doesn't hurt to really say what you mean.

    I hope you aren't one of those people who also berates others for using excess parentheses, because they "slow down the compiler" or something.

    A few years ago, I worked with this woman who was a former Lisp programmer, and she used to bury her expressions in lots of layers of parentheses, just because the compiler would effectively ignore them:

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

    On short expressions, it's not so bad, but on very complex expressions with multiply nested sub-groups, it was a horror to manually scan. I spent a whole lot of time normalizing her code
  • el jaybird 2007-01-25 10:36
    Frzr:
    atari, where you had no exceptions.


    Shaka, when the walls fell.
  • Anonymous 2007-01-25 10:40
    My favorite is the gradual maintenance that eventually results in abominations like this:

    if(!(!foo == !false))

    ... logic parse error, core dumped ...
  • Havic 2007-01-25 10:43
    I must say that I don't see a problem returning an error from the method, though I should think that you would want to catch explicit errors and only return errors you were expecting, any unknown errors could just be rethrown. In this way the calling function could check for null for success, anything else was a minor error probably indicating that the email couldn't be sent. I've done email routines this way many times. I usually just tell the user that there was a problem sending the email and then spit out the error description.
  • Jon 2007-01-25 10:44
    Fredric:

    captcha: bathe, is that even a real word?


    Ask your coworkers if you stink

    captcha: paint
  • digdug 2007-01-25 10:49
    gram:
    they also haven't heard about Regex.Replace, which makes life easier (:
    but it's true, xslt is the right way

    Nope, the Right Way is a templating language (free template or the like) rather than XML/XSLT.
  • Brian 2007-01-25 10:55
    Am I the only one to think that naming template files with an extension of .tmp is a WTF?
  • n 2007-01-25 10:58
    el jaybird:
    Frzr:
    atari, where you had no exceptions.


    Shaka, when the walls fell.



    YAYAYAAYY!!!! You made my day!

    Temba, his arms wide.

    (captcha -- xevious, one of my favorite old video games. I can still hum the theme song.)
  • htg 2007-01-25 11:07
    I must say that I don't see a problem returning an error from the method, though I should think that you would want to catch explicit errors and only return errors you were expecting

    Define your own exception, e.g., MyMailSendException, with useful fields.

    Catch email and I/O exceptions, then use them to throw your own MyMailSendException, thus protecting the code that calls your code from the email/IO/etc exceptions.

    But returning exceptions, that's nutty. However it is less CPU overhead than executing code in a try..catch statement (well, historically in Java, I don't know about now, or C#). Also simply catching the highest level Exception is not nice, that's why subclasses exist!

    This code does explain spam emails I get with %%username%% in them though.

    Catch and Release, yeah, fishy, but Catch and Return is more accurate here...
  • snoofle 2007-01-25 11:10
    n:
    el jaybird:
    Frzr:
    atari, where you had no exceptions.


    Shaka, when the walls fell.



    YAYAYAAYY!!!! You made my day!

    Temba, his arms wide.

    (captcha -- xevious, one of my favorite old video games. I can still hum the theme song.)


    Somewhat off topic, but...

    you know you're getting old when you feel old because you get not only both of these references, but the original references that came (way) before them..
  • Nurgle 2007-01-25 11:17
    if (true == HateReadableCode)
    {
    return NoCookie;
    } else if (false == HateReadableCode)
    {
    return ChocolateChip;
    } else
    {
    return FileNotFound;
    }

    captcha: mmmm... yummy cookies...
  • htg 2007-01-25 11:17
    Also shouldn't the entire regex stuff be the C# equivalent of the single line in Perl:

    $template ~= s/%%(.$)%%/$t{"$1"}/g;

    although when I've done stuff before (a few years ago, and in Perl which I'm now rusty in) I used to use {{variable}} in my templates (usually HTML, but did have email templates) instead of %%variable%%.

    Now I'd use a proper templating engine.

    %t = {
    captcha => "pirates";
    };
  • NoName 2007-01-25 11:17
    Smudge:
    Whenever I see "== true" or "== false", it's always a guarantee that the rest of the code will be awful too. This one didn't disappoint,


    Usually, I'd agree. However, I admit to having used this syntax in weakly typed languages (like Python), because I used a "trinary" variable. That is, it could be true, false, or an object. So the check "foo == true" made perfect sense, because if "foo" is an object, it will cast to "true", but that's different from foo actually being equal to true.

    However, in strongly-typed langugaes, there's no good reason for that.
  • Nurgle 2007-01-25 11:18
    Oops, forgot to qutoe above...


    Smudge:
    Whenever I see "== true" or "== false", it's always a guarantee that the rest of the code will be awful too. This one didn't disappoint,
  • Peter Antoine 2007-01-25 11:19
    snoofle:
    n:
    el jaybird:
    Frzr:
    atari, where you had no exceptions.


    Shaka, when the walls fell.



    YAYAYAAYY!!!! You made my day!

    Temba, his arms wide.

    (captcha -- xevious, one of my favorite old video games. I can still hum the theme song.)


    Somewhat off topic, but...

    you know you're getting old when you feel old because you get not only both of these references, but the original references that came (way) before them..


    I apologise for being equally as old but, http://en.wikipedia.org/wiki/Row_of_bombs.

    DevPack ST ahhhh..... the good old days. (not quite as good as DevPack on the 800XL --- now that was coding)
  • Andrew Bell 2007-01-25 11:22
    Returning exceptions isn't so nutty. Not to say that this is good code, but it could be useful. Maybe some callers will care that things failed, and some callers don't care. Those that care can check to see if an exception is returned. Those that don't care don't have to do ANYTHING. To ME, this is nicer than:

    try {
    call();
    }
    catch (Exception ex)
    {}

    Returning the exception provides everything you want to know IF you want to know it.
  • htg 2007-01-25 11:34
    Andrew Bell:
    Returning exceptions isn't so nutty. Not to say that this is good code, but it could be useful. Maybe some callers will care that things failed, and some callers don't care. Those that care can check to see if an exception is returned. Those that don't care don't have to do ANYTHING. To ME, this is nicer than:


    Or you could use a policy of "Catch And Consume" within the method and simply return a boolean, true for successfully sent, false for failed to send, and filenotfound otherwise.

    Regardless returning an Exception is silly, you might as well return any type of object, e.g., in this case a String would suffice with the error message inside.

    Or is your optional code, i.e.,

    if (exception != null) {
    if (exception instanceof FileNotFoundException) { blah }
    else if (exception instanceof EmailNotSentException) { blah }
    else ....
    else { have we tried all possible exceptions? I'm not sure, the javadoc didn't say what the possible exceptions would be, but when we use a try/catch the IDE will let us know }
    }

    really that good?

    captcha: stinky. yup, it certainly is.
  • dwm 2007-01-25 11:35
    htg:


    %t = {
    captcha => "pirates";
    };


    Your Perl really is rusty. That should be:

    %t = (
    captcha => "pirates",
    );
  • Eam 2007-01-25 11:38
    John Cowan:
    Sure, why not return an exception? It's a first-class object; you can pass it around however you like, pick it apart, whatever. Nothing says you *have* to throw it.


    Sarcasm usually doesn't come across clearly in text, so I'm going to have to assume you're not joking.

    Please stay away from all languages that treat exceptions as first-class objects.
  • Smudge 2007-01-25 11:47
    AndrewB:
    Smudge:
    Whenever I see "== true" or "== false", it's always a guarantee that the rest of the code will be awful too. This one didn't disappoint,


    Ever heard of readability?


    Ever heard of DRY? If you're going to test a boolean against a boolean to get a boolean, why stop there? Why don't you test the result of that against another boolean, just to be sure?
  • So..... 2007-01-25 11:47
    Smudge:
    Whenever I see "== true" or "== false", it's always a guarantee that the rest of the code will be awful too. This one didn't disappoint,


    Very true! One of me pet hates is when people put

    <code>if(true==isEnabled){}</code?

    I know that it stops you accidentally assigning the value but come on it is just wrong!
  • woohoo 2007-01-25 11:47
    Andrew Bell:
    Returning exceptions isn't so nutty. Not to say that this is good code, but it could be useful. Maybe some callers will care that things failed, and some callers don't care. Those that care can check to see if an exception is returned. Those that don't care don't have to do ANYTHING. To ME, this is nicer than:

    try {
    call();
    }
    catch (Exception ex)
    {}

    Returning the exception provides everything you want to know IF you want to know it.


    sorry, but no.
    it *is* nutty to return exceptions. one of the main reasons for exceptions is the fact that you are *required* to handle them (with the notable exception ;o) of runtime/unchecked exceptions, which are nevertheless always handed up the call stack and manifest themselves somewhere), and it is usually not just for the fun of it if any method throws an exception.

    if you are just returning exceptions it is even easier to just ignore or swallow them unnoticed.

    the fact that very many exceptions are indeed "handled" in the way you are insinuating in your code snippet just shows how many developers do not have the dimmest of ideas about the concepts of "their" languages. code like above should immediately result in a release - of the developer in question, that is ;o)

    thankfully modern IDEs (like eclipse e.g.) issue warnings about empty blocks, so it is easier to nail down whick devloper is to be "released"... ;o)

    captcha: sanitarium ;o))
  • Smudge 2007-01-25 11:59
    it *is* nutty to return exceptions. one of the main reasons for exceptions is the fact that you are *required* to handle them (with the notable exception ;o) of runtime/unchecked exceptions,


    ...which are all that C# has.
  • Baston 2007-01-25 12:04
    Frzr:
    "Catch and Release is more than just a way of hurting fish for fun." -- Dogbert


    Catch and Throw is far worse :o)
  • Stephen 2007-01-25 12:15
    snoofle:
    A few years ago, I worked with this woman who was a former Lisp programmer, and she used to bury her expressions in lots of layers of parentheses, just because the compiler would effectively ignore them:

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


    I learned C on a machine with 64K RAM. That compiler had a quirk: every time it ran into an open-parenthesis or a left-curly-bracket, something inside it recursed, with neither a recursion limit nor stack bounds-checking. Its behavior under stack overflow usually wasn't to crash. Instead it would generate bad code. (Oh, the second half of my function? I guess I didn't need it anyway... That illegal assembly code the compiler generated? It must be the assembler's problem...)

    If your coworker's post-death fate should be the firey place down below, that old compiler is probably waiting for her. :-)
  • Anon 2007-01-25 12:20
    I will stand up and defend if(false==something) because, personally, I read code like this:

    if (something happens) {
    do something;
    }

    If the statement in the if is required to be false that is *abnormal*, and I don't like to include anomalies in my code without making them highly visible.

    Doing if(true==something) is retarded, though.
  • htg 2007-01-25 12:26
    dwm:
    htg:


    %t = {
    captcha => "pirates";
    };


    Your Perl really is rusty. That should be:

    %t = (
    captcha => "pirates",
    );


    I saw that after posting, no edit functionality! (I had written $t{'captcha'} = "pirates"; and decided to change it, honest!)
  • webdev101 2007-01-25 12:45
    snoofle:
    Odhran:
    What a bloody awful piece of code!!

    They obviously never heard of XSL transforms either ... for shame!

    Yeah, because someone who would write something like this needs to be turned loose with XSLT...

    ... not saying XSLT is the wrong way, just this seems like the wrong person to attempt to use it!


    more like wrong person to attempt to use anything!
  • Betta Glurpse 2007-01-25 12:48
    Anon:
    I will stand up and defend if(false==something) because, personally, I read code like this:

    if (something happens) {
    do something;
    }

    If the statement in the if is required to be false that is *abnormal*, and I don't like to include anomalies in my code without making them highly visible.

    Doing if(true==something) is retarded, though.


    Well - it might make sense to you personally because it's your personal style, but if *I* read "false==", the only abnormality I see is a coder who doesn't know his language. Why not just write "if (!condition)" if there is a condition you want to be false?

    To me, "if (!condition") reads "if not condition", and I think it is much clearer to me than "false==condition", which I read (at best) "if false is condition".
  • Betta Glurpse 2007-01-25 12:59
    Hehe, this is a really good laugh.
  • cconroy 2007-01-25 13:00
    Fredric:

    captcha: bathe, is that even a real word?


    Alex Trebek: Doctors recommended taking one of these at least once a day.
    Beavis: What is a shower?
    Butt-head: Dude, if you have to ask, you'll never know.
  • Shazam 2007-01-25 13:27
    RE: String replace. Completely missed the boat. I guess it might work, but I hope it doesn’t process a lot of emails. Perhaps it’s a spam mailer and the angelic developer intentionally wanted to make it as slow as possible.

    RE : Exceptions
    1. It’s the wrong way to use an exception. The caller of SendMail could have used their own Try/Catch block to better effect and stuck with the right pattern.
    2. Exceptions are for exceptional circumstances. If you want to return a status and expect it may fail, just create a new object. Using an exception class (especially the base exception class) is an abortive use of exceptions. Considering this code did exactly nothing with the exception just makes it worse.
    3. It catches all exceptions. So how is the calling code going to react with an OutOfMemoryException or ThreadAbortException occurs? A big switch statement? Catch specific exceptions whenever possible. Exceptions are usually a big flashing light that something is wrong.

    If you really really really need to quash those exceptions, it could at least be written in a more canonical form:


    void SendMail(
    string template,
    Person sender,
    Person receiver,
    string subject)
    {
    // horrific implementation without try/catch
    }

    bool TrySendMail(
    string template,
    Person sender,
    Person receiver,
    string subject)
    {
    bool success = true; // true optimism
    try
    {
    SendMail(template, sender, receiver, subject);
    }
    catch( SmtpException ex )
    {
    success = false;
    LoggingFramework.LogException(this, ex);
    // quashing exception. method does NOT re-throw
    }
    return success;
    }


    PS I cannot say I dig this, but sometimes it makes sense.

    If the dev’s are really that allergic to the try/throw semantics of exceptions they would be better to return their own object and leave poor exceptions alone:


    public class SendMailResult
    {
    public enum ResultStatus
    {
    Okay = 0,
    BadSender = 1,
    BadRecipient = 2
    // add more as necessary
    }

    // data
    private string description;
    private ResultStatus result;

    // constructors
    private SendMailResult() { }
    public SendMailResult(ResultStatus resultStatus, string description)
    {
    this.result = resultStatus;
    this.description = String.IsNullOrEmpty(description) ? string.Empty : description;
    }

    // properties - immutable object - no setters
    public ResultStatus Result
    {
    get { return this.result; }
    }
    public string Description
    {
    get { return this.description; }
    }

    // methods
    public bool Success()
    {
    return this.Result == ResultStatus.Okay;
    }

    public bool Failed()
    {
    return !Success();
    }
    }
  • EvanED 2007-01-25 13:46
    htg:
    However it is less CPU overhead than executing code in a try..catch statement (well, historically in Java, I don't know about now, or C#).


    That depends on the implementation, and how often exceptions are thrown. I don't know how Java or C# does it, but it's possible (and I think at least sometimes done) to compile exceptions in such a way that if an exception isn't thrown there is NO overhead... it's as if the "try{" "}" and catch blocks were completely removed.

    htg:
    Also shouldn't the entire regex stuff be the C# equivalent of the single line in Perl:

    $template ~= s/%%(.$)%%/$t{"$1"}/g;


    I thought people frowned upon write-only languages.

    (Half kidding...)

    Betta Glurpse:
    Well - it might make sense to you personally because it's your personal style, but if *I* read "false==", the only abnormality I see is a coder who doesn't know his language. Why not just write "if (!condition)" if there is a condition you want to be false?


    Not the original poster, but a possible argument for 'false==' is that if you're skimming the code it can be very easy to miss the !, especially if it's snuggled between some parens like 'if(!(...))'

    shazam:
    So how is the calling code going to react with an OutOfMemoryException or ThreadAbortException occurs?


    I don't know about the ThreadAbortException, but the OutOfMemory"Exception" is actually the OutOfMemoryError, and isn't a subclass of Exception.

    Here's a pretty picture:


    class Throwable
    |
    |--- class Exception
    |
    |--- class Error
    |
    |--- class VirtualMachineError
    |
    |--- class OutOfMemoryError
  • sf 2007-01-25 13:47
    Cyrus:
    I don't think they quite understand stack unwinding; though I'm interested to hear someone defend this, could be interesting.

    Captcha: Bling, word.

    I'll take a wack at defening this to a certain extent. Say this method is invoked asycronously within a separate thread from the one executing some business process of some kind. Perhaps during this process multiple email messages (or an email, pager, and recipient home page update) must be sent out simultaneously, and that each of these requests are forked as separate threads or passed to a thread pool and the main thread waits for their completion.

    Now, it would make no sence for each emailing thread to throw an exception since the waiting main processing thread can never catch it. Often in this case the result of the asynchronous execution is saved after processing, or the exception object itself is save when there is a failure, so that all of results of the asynchronous operations (including the exceptions that caused failures) can be collected together and handled by the main thread.

    Of course it would have been better not to implement SendMail with threading in mind. It would be better to have the "thread aware" code that wraps this call to catch and store the exception object. Plus, it's IS silly to return the exception if instead of throwing if something like a threads are NOT involved.

    Sorry for the long reply.
  • gwenhwyfaer 2007-01-25 13:52
    Fredric:
    captcha: bathe, is that even a real word?


    *makes sure to stand a good six feet upwind of Fredric*

    ...realising in dismay that the use of the term "upwind" is certain to provoke another interminable debate about whether it's correct... *sigh*
  • Jax 2007-01-25 13:55
    It's worth noting that in .NET 2 and up an unhandled exception on a separate thread from the main one will cause the entire application to fall over and die, horribly.

    That said, i'd still do the catching elsewhere, or rename the method "TrySendMail" with an out parameter for the exception (like TryParse).
  • gwenhwyfaer 2007-01-25 13:56
    snoofle:
    I spent a whole lot of time normalizing her code


    How did you explain the time you spent correcting all the bugs you introduced?
  • Jax 2007-01-25 14:02
    I don't know about the ThreadAbortException, but the OutOfMemory"Exception" is actually the OutOfMemoryError, and isn't a subclass of Exception.


    Not in my version of C# (2.00).
    I know that they previously recommended using ApplicationException in V1 but they dropped that and Exception is again the "true" daddy.
    I'm checking the type: OutOfMemoryException in VS2005 and it's telling me it's a subclass of SystemException which is a subclass of Exception


    class Exception

    |

    |--- class SystemException

    |

    |--- class OutOfMemoryException
  • Jax 2007-01-25 14:04
    Sorry my formatting was all of:

    class Exception

    |

    |--- class SystemException

    -----|

    -----|--- class OutOfMemoryException
  • gwenhwyfaer 2007-01-25 14:04
    Eam:
    Sarcasm usually doesn't come across clearly in text, so I'm going to have to assume you're not joking.

    Likewise, when I notice that my freshly opened yoghurt pot is now half empty and my pet cat is washing her whiskers, I always assume that some elves ran in, stole my yoghurt, and tossed her a cat treat so she wouldn't eat them.

    It makes perfect sense, and one day I WILL catch those elves.
  • gwenhwyfaer 2007-01-25 14:08
    Smudge:
    If you're going to test a boolean against a boolean to get a boolean, why stop there?

    Indeed:
    bool isTrue(bool isit) { return isit == true ? true : false; }
    
    bool isFalse(bool isit) { return isTrue(isit) != false ? false : true; }
  • Kemp 2007-01-25 14:17
    snoofle:
    I spent a whole lot of time normalizing her code


    Why did that sound like innuendo the first (and every subsequent) time I read it?

    "Yeah, I normalized her code all night." *wink* *wink*
  • its me 2007-01-25 14:46
    Jax:
    I don't know about the ThreadAbortException, but the OutOfMemory"Exception" is actually the OutOfMemoryError, and isn't a subclass of Exception.


    Not in my version of C# (2.00).


    The example was java, the Throwable object was the clue.... In C# it is an exception....
    -Me
  • WWWWolf 2007-01-25 14:57
    This particular bit of code reminds me of that scene where that guy was shooting the "bullet-dodger" guy in the movie Snatch.

    Body: "Arrrgh... %%username%% %%password%%..."
    Guy: (pulls out the replacer gun and shoots the message body)
    *BLAM*
    Guy: (Turns away)
    Body: "Urrgh... %%password%%, almost had me there..."
    Guy: (Turns around and shoots the message body)
    *BLAM BLAM BLAM BLAM*
    Body: "Arrgh..."
    *BLAM BLAM*
    Guy: (Thinks all of the replacements have finally been made in the body and turns around to see an Exception. Tries to shoot it, and...)
    *Click!*

    I mean, I haven't looked at the C# library, but I take it C# isn't completely awful and actually has the equivalent of Perl's /g modifier on s///, or Ruby's String#gsub ? No need to go looping around and doing complete replace on the *entire* message body until you no longer get matches...

    At least the regex is compiled only once...
  • Hans 2007-01-25 15:22
    willy:
    Smudge:
    Whenever I see "== true" or "== false", it's always a guarantee that the rest of the code will be awful too. This one didn't disappoint,


    I dunno, in any language I try to make things as explicit as possible. having '== true' or whatever (although a bit redundant makes it obvious as to what the return type is being evaluated in the conditional without the need to investigate further.

    I do a lot of code maintenance, so maybe it's just me, but when I'm skimming through existing code after its been written, little visual queues like this save time and brainpower.


    Ahhh, we have an unbeliever among us! So if you see a perfectly valid boolean expression like

    if (a) { ... }

    you don't trust it and would prefer to write

    if (a == true) { ... }

    But surely you recognize that this is still a boolean expression, as much subject to misinterpretation as the first one? So why do you persist in this misguided believe that having just one boolean expression is enough? To be truly sure, you would need to write this:

    if ((a == true) == true) { ... }

    Or better still

    if (((a == true) == true) == true) { ... }

    There! That is far more clear, and in case boolean logic fails us the first time we have backups in place!

    ...

    Ok, so I'm making fun of you, but it is meant in good spirit. Obviously I don't like this kind of redundancy, and instead of sprinkling them through the code I delete them wherever I find them ;-)

  • Konstantin Surkov 2007-01-25 15:28
    As (I am sure) everybody knows, there are two different ways to handle errors. One is through exceptions, another one is through error codes. This snippet is actually a fine example of the smooth transition of one into another.
  • EvanED 2007-01-25 15:31
    Jax:
    I don't know about the ThreadAbortException, but the OutOfMemory"Exception" is actually the OutOfMemoryError, and isn't a subclass of Exception.


    Not in my version of C# (2.00).


    Ha! That's 'cause I'm stupid. I'm apparently in Java mode. No wonder I couldn't find anything about ThreadAbortException.

    Sorry 'bout that...
  • EvanED 2007-01-25 15:38
    gwenhwyfaer:
    Smudge:
    If you're going to test a boolean against a boolean to get a boolean, why stop there?

    Indeed:
    bool isTrue(bool isit) { return isit == true ? true : false; }
    
    bool isFalse(bool isit) { return isTrue(isit) != false ? false : true; }


    No no no...

    public boolean checkFalse(Boolean bool)
    
    {
    if (bool.booleanValue() == Boolean.FALSE.booleanValue())
    {
    return Boolean.FALSE.booleanValue();
    }
    else
    {
    return Boolean.TRUE.booleanValue();
    }
    }

    http://thedailywtf.com/Articles/A_False_Detector.aspx
  • Konstantin Surkov 2007-01-25 15:46
    Well, that's true if "some callers don't care", but it should be awfully laid back system for the callers to not care whether the function they called succeeded or failed. I think the new fashionable term for that is "loosely coupled" :-)
  • snoofle 2007-01-25 15:47
    gwenhwyfaer:
    snoofle:
    I spent a whole lot of time normalizing her code


    How did you explain the time you spent correcting all the bugs you introduced?

    I didn't need to. I tend to use JUnit a whole lot, so I made up a bunch of test cases (upper & lower limits, edge cases, error conditions, etc) and got a known set of results. Then refactored and reran the cases and programmatically matched the results.

    If you test thoroughly, you can be reasonably confident of your results before you break anything (I've been doing this a very long time; not saying I'm perfect, but I tend to be very thorough).
  • snoofle 2007-01-25 15:59
    JCM:
    Yeah, true and false look absolutely wierd as lvalues.


    Take it to the next level:


    Boolean result = (FileNotFound == Boolean.valueOf("true")
    ? wtf.spewForth()
    : !!!!!!!!!!!!!Boolean.FileNotFound);
  • Satanicpuppy 2007-01-25 16:08
    Smudge:
    AndrewB:
    Smudge:
    Whenever I see "== true" or "== false", it's always a guarantee that the rest of the code will be awful too. This one didn't disappoint,


    Ever heard of readability?


    Ever heard of DRY? If you're going to test a boolean against a boolean to get a boolean, why stop there? Why don't you test the result of that against another boolean, just to be sure?


    I personally have a tendency, when confronted with some torturous piece of boolean logic, to say:

    bVal = (!(blah blah blah) || ((BLAH BLAH) && (Blah)) && ( Blah() || Blah()));

    if(bVal){doSomething};

    rather than try and put that whole chunk of logic in my conditional. I agree with "==True" though.
  • al 2007-01-25 16:13
    No one else finds it to be a wtf that it's searching for instances of %%username%% in the body, then if he sees one, he runs a global replace for a single instance of %%username%% (which, of course, does another search from the start again to find it). This in turn creates another instance of body while the foreach loop is still iterating over matches in the original instance of body. And this happens for EACH token!

    Presumably the entire method, loops, switches, and all, can be replaced by
    Body = Body.ReplaceAll("%%username%%", Receiver.UserName);
    Body = Body.ReplaceAll("%%password%%", Receiver.Password);
    ...

    And why are they putting passwords in email? And THEN there's the exception thing!
  • Your Name 2007-01-25 17:54
    snoofle:
    gwenhwyfaer:
    snoofle:
    I spent a whole lot of time normalizing her code


    How did you explain the time you spent correcting all the bugs you introduced?

    I didn't need to. I tend to use JUnit a whole lot, so I made up a bunch of test cases (upper & lower limits, edge cases, error conditions, etc) and got a known set of results. Then refactored and reran the cases and programmatically matched the results.

    If you test thoroughly, you can be reasonably confident of your results before you break anything (I've been doing this a very long time; not saying I'm perfect, but I tend to be very thorough).

    I apologize if my post earlier contributed to putting you on the spot this entire time. You obviously know what you are doing.

    It was my failure to assume that programmers in general have a hint of understanding about binary (or formal) logic and could be trusted to come up with reasonable expressions, if even he or she didn't completely understand the order of operations (operator priority) in a given language or maybe refused to use (-, ~, NOT, <>, or !=).
  • Gaurav 2007-01-25 18:04
    I just got into work today (extra-early, gah) and this code block was the first thing I saw :(. What a horrible way to start the day.
  • Jackal von ÖRF 2007-01-25 18:04
    EvanED:
    htg:
    However it is less CPU overhead than executing code in a try..catch statement (well, historically in Java, I don't know about now, or C#).


    That depends on the implementation, and how often exceptions are thrown. I don't know how Java or C# does it, but it's possible (and I think at least sometimes done) to compile exceptions in such a way that if an exception isn't thrown there is NO overhead... it's as if the "try{" "}" and catch blocks were completely removed.

    In Java if you override the java.lang.Throwable#fillInStackTrace method, the big overhead of creating exceptions goes away. I've even heard that the VM itself would internally use exceptions for some flow control. I did a micro benchmark, and throwing exceptions without a stack trace is some 20 times faster than throwing normal exceptions: ExceptionSpeedTest.java (In a real life situation, the overhead of building the stack trace should be much higher, because there are more method calls in the stack)

    I don't know about C#.

    Addendum (2007-01-25 18:34):
    PS: I noticed that creating exceptions (normal ones, with stack trace) is about twise as fast under Java 6 than under Java 5 (my previous test was with Java 5). It seems that Sun has managed to speed up the building of the stack trace.

    Addendum (2007-01-25 18:59):
    The overhead of try-catch blocks, when not throwing exceptions, should be a problem only when the try-catch is inside a loop/hotspot. The overhead is in entering/exiting the try-catch block, and not in running code inside the block.

    Quoted from http://www.mortench.net/blog/2006/08/08/dos-and-donts-for-exception-handling-or-what-every-developer-should-know-about-the-implementation-of-exception-handling/
    "Specifically, the case of overhead of try-catch-finally constructions when no exceptions occur is difficult to get rid of by compiler & virtual-machine implementers. [--] Basically this is because something like a “linked list” has to be maintained internally by the compiler or VM each time the control flow enters or exits a try-catch-finally."
  • verisimilidude 2007-01-25 18:06
    I think the reason for returning the exception is that the SmtpMail class in .NET throws exceptions for a lot of things and the programmer didn't want to mess up his code caring about them. The caller can unpack the messy result if the mail service is down, the network is down, DNS is down, etc.
  • Zygo 2007-01-25 18:15
    willy:
    Smudge:
    Whenever I see "== true" or "== false", it's always a guarantee that the rest of the code will be awful too. This one didn't disappoint,


    I dunno, in any language I try to make things as explicit as possible. having '== true' or whatever (although a bit redundant makes it obvious as to what the return type is being evaluated in the conditional without the need to investigate further.

    I do a lot of code maintenance, so maybe it's just me, but when I'm skimming through existing code after its been written, little visual queues like this save time and brainpower.


    I do work in a number of different languages (usually 2-3 in a typical day, dozens per year). I'm what Fred Brooks would call a "language lawyer."

    // Suppose we start with:
    foo = someFunction();

    // return #1:
    return foo;
    // return #2:
    if (foo) { return true; } else { return false; }
    // return #3:
    if (foo == true) { return true; } else { return false; }
    // return #4:
    if (foo != true) { return false; } else { return true; }
    // return #5:
    if (foo == false) { return false; } else { return true; }

    In some languages you get different results from some of the statements. In a few languages you can get different results from *three or more* of the statements depending on the return type of someFunction() or properties of its value. (Examples: suppose the return value is NULL in SQL, undef in Perl, or an int >= 2 in C++)

    I've encountered most of the 16 possible cases of pairs of languages where the coder was thinking in language A, but writing in language B, and the coder's expectations did or did not match the language's semantics in one of the cases (most often the one they actually used, which is how I come to be looking at the code in the first place).

    To me, "if (something == true)" means something very different from "if (something)". I will spend mental cycles trying to figure out why the unnatural "== true" form was used over the more obvious "something" form, because someone went to extra effort to add an equality comparison operator with a boolean operand to a value that was already boolean or evaluated in a boolean context. I start wondering what the hell the type of "something" is and why does it behave so differently when used this way that it was necessary to add code to work around it. This mental process happens to me even if the language doesn't have operator overloading, or a boolean type for that matter.
  • Zygo 2007-01-25 18:29
    htg:
    Also shouldn't the entire regex stuff be the C# equivalent of the single line in Perl:

    $template ~= s/%%(.$)%%/$t{"$1"}/g;


    More like:

    $template =~ s/%%([^%]+)%%/defined($t{$1})?$t{$1}:$&/geos;

    unless you want unknown variables to be stripped out of the output.

    Also, the one-line Perl version is different from the original code. In the original code, if your template variable values contained further template variable references, they would be expanded too, at various times (exactly when is left as an exercise for the reader--I tried writing an explanation here, but three paragraphs later I still haven't got an accurate description of what it does and when...).
  • Zygo 2007-01-25 18:34
    Andrew Bell:
    Returning exceptions isn't so nutty. Not to say that this is good code, but it could be useful. Maybe some callers will care that things failed, and some callers don't care. Those that care can check to see if an exception is returned. Those that don't care don't have to do ANYTHING.


    So in other words I'd have to wrap the SendMail object like this:

    public void SendMailWrapper(...) {
    Exception foo = SendMail(...);
    if (foo != null) {
    throw foo;
    }
    return;
    }
  • Zygo 2007-01-25 18:41
    EvanED:
    Not the original poster, but a possible argument for 'false==' is that if you're skimming the code it can be very easy to miss the !, especially if it's snuggled between some parens like 'if(!(...))'


    Only if you're using a proportional font for reading code, which is a WTF in itself...
  • Zygo 2007-01-25 18:43
    gwenhwyfaer:
    Fredric:
    captcha: bathe, is that even a real word?


    *makes sure to stand a good six feet upwind of Fredric*

    ...realising in dismay that the use of the term "upwind" is certain to provoke another interminable debate about whether it's correct... *sigh*


    feet, are those even a real unit of measure?
  • Mcoder 2007-01-25 18:45
    al:
    Presumably the entire method, loops, switches, and all, can be replaced by
    Body = Body.ReplaceAll("%%username%%", Receiver.UserName);
    Body = Body.ReplaceAll("%%password%%", Receiver.Password);


    Now you don't have the Exception value to return... What a bad style.
  • Zygo 2007-01-25 18:46
    Hans:

    if (((a == true) == true) == true) { ... }

    There! That is far more clear, and in case boolean logic fails us the first time we have backups in place!


    GAH!

    if (a == true == true == true) { ... }

    Fsckin' useless parens...





    ;-)
  • Chris 2007-01-25 18:49
    Actually, yours isn't stellar.

    my %t ...
  • ehren 2007-01-25 19:25
    "Do you have to turn everything into a double-entendre?"

    "No..."

    *later*

    "I'd like to double [i]her[\i] entendre!"
  • darwin 2007-01-25 19:55
    Andrew Bell:
    Returning exceptions isn't so nutty. Not to say that this is good code, but it could be useful. Maybe some callers will care that things failed, and some callers don't care. Those that care can check to see if an exception is returned. Those that don't care don't have to do ANYTHING. To ME, this is nicer than:

    try {
    call();
    }
    catch (Exception ex)
    {}



    God, you're an idiot. Why would you think that would be the only alternative? Why would you think returning Exception would be the answer?

    If there are really some callers who care whether the call to send the mail succeeded, and some who don't, you could easily do this:


    public boolean sendMail(...) {
    try {
    // ... send the mail
    return true;
    } catch (SomeException e) {
    log(e);
    }
    return false;
    }


    But if that isn't good enough for you, because the callers who care really want to see the Exception for themselves, then you could still just do this:


    public void sendMail(...) throws SomeException {
    // ... send the mail
    }

    public void fireAndForget(...) {
    try {
    sendMail(...);
    } catch (SomeException e) {
    log(e);
    }
    }


    That way, the callers who don't care about the exception can just call fireAndForget(), and they don't need to wrap it up in a try/catch block.

    No matter what, returning Exception is so deeply, truly, madly wrong that I find it hard to imagine how someone even thought of it, much less wrote it. WTF?!?

    captcha: yummy. Should have been "yucky" instead.
  • Vexorian 2007-01-25 21:21
    ok,
    1) Returning an exception is not all right, it does not matter if they are first class objects, it is an anti pattern, it is like going back to the error code world yet still use exceptions.

    2) ==true and ==false do not really make code more readable, The if syntax is most of the times if (boolean) ... so if anything they just take more space.
  • chrismcb 2007-01-25 21:26
    AndrewB:
    Smudge:
    Whenever I see "== true" or "== false", it's always a guarantee that the rest of the code will be awful too. This one didn't disappoint,


    Ever heard of readability?


    There is readability and then there is reading for the sake of readability.

    More stuff doesn't always make something easier to understand. It means more reading, and more parsing.

    If you are an ok programmer, you know its if (statement1) statement2 else statement3. You know statement2 will be executede if statement1 is true. Is it really necessary to say "if (statement1 = true)???? As you read this, you have to read the = true thing.

    Adding == true or == false doesn't help the readability.

    And yes adding parenthesis can help readability, but it can also hinder it.


    Everyone needs water, but you can still drown in it.
  • cklam 2007-01-25 21:56
    Betta Glurpse:
    Anon:
    I will stand up and defend if(false==something) because, personally, I read code like this:

    if (something happens) {
    do something;
    }

    If the statement in the if is required to be false that is *abnormal*, and I don't like to include anomalies in my code without making them highly visible.

    Doing if(true==something) is retarded, though.


    Well - it might make sense to you personally because it's your personal style, but if *I* read "false==", the only abnormality I see is a coder who doesn't know his language. Why not just write "if (!condition)" if there is a condition you want to be false?

    To me, "if (!condition") reads "if not condition", and I think it is much clearer to me than "false==condition", which I read (at best) "if false is condition".


    my choice is: "if not condition" rather than " if (! condition". I personally find it more readable ....
  • Jimmy Jones 2007-01-26 03:30
    I don't think returning an Exception is a true WTF, think of it as a "boolean with added explanation".

    All the rest of it though ... where to begin???

  • Baggy McBagster 2007-01-26 04:25
    The real wtf is that they have local variables that begin with a capital letter as if they were type names. Why do people _do_ that?

  • Monkeyget 2007-01-26 04:39
    htg:
    But returning exceptions, that's nutty. However it is less CPU overhead than executing code in a try..catch statement (well, historically in Java, I don't know about now, or C#).

    In C# (.NET actually) there is absolutely no overhead when running code in a bunch of try..catch..finally.

    While i'm at it and contrary to what's wildly believed, throwing exception is not (that) slow. With a stack of 1000 (1000 method calls recursively!!!) I was able to throw and catch 70 exceptions...by millisecond. And that was in debug mode, with the framework 1.1 on a not so fast machine.

    However, when an application is run under visual studio and with the debugger (I'm not talking about debug-release but just running it with the debugger) then it's awfully slow. That's where the myth might come from.

    I'd be interested to know what it's like with Java.
  • Anders 2007-01-26 04:57
    Smudge:
    Whenever I see "== true" or "== false", it's always a guarantee that the rest of the code will be awful too. This one didn't disappoint,


    In the type of languages as C#, sure. But if you're programming general-purpose C and similiar languages there's a point of doing == TRUE and == FALSE. I've seen systems where TRUE is 0 and FALSE is 1 and you'd be suprised how interesting problems you can get when someone think they can just do if (a) and if (!a) as "normal".
  • Jimbo 2007-01-26 06:44
    %%SomeWord%% -> knowing 4% of regex functionnalities ?
  • Betta Glurpse 2007-01-26 07:10
    This is C#.

    To all of you who think ==true makes stuff more readable:

    There is NEVER a good reason to do an if (...==true or even ...==false ). If you think you are making the if more readable, it shows that at least one of these apply:

    a) you are not comfortable with the if-else statement (bad), or

    b) you are not comfortable with boolean logic (bad), or

    c) you are thinking in another language (bad), or

    d) you think that by adding ==true or ==false you can make it clear to others who aren't comfortable with if-else and boolean logic how these things work (noble, but it shouldn't be necessary and disturbs programmers who do understand), or

    e) you think it makes your intention clearer (wrong), or

    f) you are twisted and you want to hurt us (very bad)

    Programmers should really, really, really, understand boolean logic and if statements. If they don't, there's a good chance there are other fundamentals they don't understand.
  • templäd 2007-01-26 07:44
    The correct way to call the method!

    try
    {
    throw SendMail();
    }
    catch (Exception ex)
    {
    if (ex is NullReferenceException)
    {
    //'everything' is ok maybe
    Console.WriteLine("OK");
    }
    else
    {
    Console.WriteLine("Oh ERROR");
    }
    }
  • Bill 2007-01-26 13:51
    verisimilidude:
    I think the reason for returning the exception is that the SmtpMail class in .NET throws exceptions for a lot of things and the programmer didn't want to mess up his code caring about them. The caller can unpack the messy result if the mail service is down, the network is down, DNS is down, etc.


    That would be a pretty big WTF in and of itself. The caller shouldn't have to wade through the various errors to decide what to do. That should be handled in the function.

    However, I have little doubt that the coder took the approach you suggest, but mostly out of laziness.

    Most cases of poor error handling that I've encountered over the years is because the coder was too lazy to handle all the cases correctly.
  • Bob Holness 2007-01-26 14:25
    Unlike Java, in .NET there is no stack trace until it is thrown.
  • Bill 2007-01-26 15:02
    Betta Glurpse:
    This is C#.

    To all of you who think ==true makes stuff more readable:

    ...

    Programmers should really, really, really, understand boolean logic and if statements. If they don't, there's a good chance there are other fundamentals they don't understand.


    I think you're confusing readable and understandable. The original claims made here in favor of '==true' were based on being easier to read, and I think that (a) they ring true, and (b) who gets to be the judge of what others find more readable?

    I know that these tired eyes have missed a '!' on more than one occasion, especially nested inside parens as mentioned here. In my 20+ years of programming, I've always tried to steer clear of the 'punctuation-style' operators when possible, as they DO slow down reading as opposed to more lengthy operators. Notice I again said "reading", not "understanding".

    One of my "rules" developed over the years is to ALWAYS remember that code is usually "write once, read many". YMMV.

  • anony-mouse 2007-01-26 16:00
    This site has gone downhill in the past couple months. I cant stand these watered down WTFs anymore.

    captcha: stinky, like this site's recent content
  • Steve 2007-01-26 17:17
    When does rookie initiation take place?
  • Betta Glurpse 2007-01-26 17:36
    Steve:
    When does rookie initiation take place?

    Duh... In the rookie initializer, or in the constructor of the enclosing class, of course :)
  • AdT 2007-01-26 18:36
    Holy excrement... why not use this method instead?
  • Betta Glurpse 2007-01-26 19:19
    Bill:
    I know that these tired eyes have missed a '!' on more than one occasion, especially nested inside parens as mentioned here.
    Just use five or seven, !!!!!, then you can't miss'em (ok, just being funny here :-))
    In my 20+ years of programming, I've always tried to steer clear of the 'punctuation-style' operators when possible, as they DO slow down reading as opposed to more lengthy operators. Notice I again said "reading", not "understanding".
    I can follow your argument about punctiation-like constructs being harder to read. As an example, of the two corresponding constructs below, the foreach version is easily more readable even though it is more verbose:
    foreach element in list          (C#)
    
    for element : list (Java)

    My counterargument on the readability issue is that
    if (!SelectionIsValid)
    reads like plain English to me - "if not the selection is valid...", whereas
    if (SelectionIsValid == false)
    reads like wierd courtroom English ("if it is false that the selection is valid..."). While redundant syntax can help readability, you can also drown in it.

    One of my "rules" developed over the years is to ALWAYS remember that code is usually "write once, read many". YMMV.
    We agree on that one.

    Bill:
    I think you're confusing readable and understandable. The original claims made here in favor of '==true' were based on being easier to read, and I think that (a) they ring true, and (b) who gets to be the judge of what others find more readable?
    Now for the part about understanding: Your stand on the readability of ==false versus ! is a conscious choice, having understood both ways. In my experience, that separates you from most of the ==false-proponents.

    Why ==false gives away an unskilled programmer:I was an assistant teacher in beginners and intermediate programming courses at the university some years ago, and overwhelmingly, the students who felt the urge to add "== false" to their boolean expressions were the ones that didn't quite understand boolean logic. Because they weren't comfortable with the boolean logic, they felt that they somehow needed to spoon feed the compiler with verbose instructions: "now, compiler, you need to take that a==b-thing, and check whether it was false, ok?". It wasn't a conscious choice. They were the same students that didn't quite understand how to use loops, and wrote code like
    StrutYourStuff();
    
    while (theStuffWasStruttedRight == false)
    {
    StrutYourStuff();
    }
    and generally would write code much like in today's WTF.

    Today I work with many skilled colleagues, and I rarely see such redundant "explanations" for the compiler. But quite recently I visited another project, with ==false redundancies sprinkled liberally around the code base. My alarm bells rang, and sure enough: The project had next to no automated test, loads of errors, loads of copy-paste-edited code, no documentation... Is it a coincidence? Naah!

    So, basically, every experience I have ever had with coding has shown that ==false and WTFiness go hand in hand.

    And just to finish off: Even if I cannot judge what others find more readable, I have a pretty good guess in this case (does the first statement even do what we want it to?):
    if (a == b == false)
    
    if (!( a == b))
    if (a != b)
  • Betta Glurpse 2007-01-26 19:23
    Betta Glurpse:
    foreach element in list          (C#)
    
    for element : list (Java)

    Whoops, forgot the parentheses. Should also have added them to that a == b == false thing to be fair.
  • Valerion 2007-01-27 04:13
    Of course, in my opinion
    if (a)
    is the right way.

    if (FALSE == a)
    has one advantage above
    if (a == FALSE)
    in C/C++, the compiler won't allow you to do

    if (FALSE = a)
    but it will be quite content with
    if (a = FALSE)
    I have seen that WAY too often. And so hard to spot at times.
  • Anonymous P.M.Doubleday 2007-01-27 17:20
    Bill:
    Betta Glurpse:
    This is C#.

    To all of you who think ==true makes stuff more readable:

    ...

    Programmers should really, really, really, understand boolean logic and if statements. If they don't, there's a good chance there are other fundamentals they don't understand.


    I think you're confusing readable and understandable. The original claims made here in favor of '==true' were based on being easier to read, and I think that (a) they ring true, and (b) who gets to be the judge of what others find more readable?

    I know that these tired eyes have missed a '!' on more than one occasion, especially nested inside parens as mentioned here. In my 20+ years of programming, I've always tried to steer clear of the 'punctuation-style' operators when possible, as they DO slow down reading as opposed to more lengthy operators. Notice I again said "reading", not "understanding".

    One of my "rules" developed over the years is to ALWAYS remember that code is usually "write once, read many". YMMV.



    Damn right, mate. Unfortunately, following this perfectly sensible rule would result in doom for 90% of the idiots who post answers here. And they're probably in the top 10% of softare professionals anyway.

    Happy, happy, happy.

    (Captcha: gotcha. Well, no, I'm afraid you'll have to try a little harder...)
  • Anonymous P.M.Doubleday 2007-01-27 17:24
    gwenhwyfaer:
    Fredric:
    captcha: bathe, is that even a real word?


    *makes sure to stand a good six feet upwind of Fredric*

    ...realising in dismay that the use of the term "upwind" is certain to provoke another interminable debate about whether it's correct... *sigh*

    Yes, it's correct. End of thread.

    PS Alex: WTF is "onomatopoeia"? Hell, I've got an A-Level in Ancient Greek, and even I find this one difficult to type in ..
  • Alchymist 2007-01-27 20:08
    snoofle:
    n:
    el jaybird:
    Frzr:
    atari, where you had no exceptions.


    Shaka, when the walls fell.



    YAYAYAAYY!!!! You made my day!

    Temba, his arms wide.

    (captcha -- xevious, one of my favorite old video games. I can still hum the theme song.)


    Somewhat off topic, but...

    you know you're getting old when you feel old because you get not only both of these references, but the original references that came (way) before them..


    Getting references to the epic of Gilgamesh. Now that's old!
  • BAReFOOt 2007-01-27 20:48
    So are you so stupid or am i so smart that i think it's perfectly readable without that "== bool"?
    Maybe poeple who need this only *think* they know the language. There's more to it. There is no spoon...
  • BAReFOOt 2007-01-27 20:50
    Damn, this was a reply. The forum really is the biggest wtf.

    BAReFOOt:
    AndrewB:
    Smudge:
    Whenever I see "== true" or "== false", it's always a guarantee that the rest of the code will be awful too. This one didn't disappoint,


    Ever heard of readability?


    So are you so stupid or am i so smart that i think it's perfectly readable without that "== bool"?
    Maybe poeple who need this only *think* they know the language. There's more to it. There is no spoon...
  • devdas 2007-01-28 11:49
    PS Alex: WTF is "onomatopoeia"? Hell, I've got an A-Level in Ancient Greek, and even I find this one difficult to type in ..

    http://en.wikipedia.org/wiki/Onomatopoeia
  • Zahlman 2007-01-28 16:58
    AndrewB:
    Smudge:
    Whenever I see "== true" or "== false", it's always a guarantee that the rest of the code will be awful too. This one didn't disappoint,


    Ever heard of readability?


    Yes, I have heard of readability.

    ...Oops. According to your version of "readability", that should be:

    "Yes, it is true that I have heard of readability."

    Sheesh.
  • Earl Purple 2007-01-29 07:38
    Anders:
    Smudge:
    Whenever I see "== true" or "== false", it's always a guarantee that the rest of the code will be awful too. This one didn't disappoint,


    In the type of languages as C#, sure. But if you're programming general-purpose C and similiar languages there's a point of doing == TRUE and == FALSE. I've seen systems where TRUE is 0 and FALSE is 1 and you'd be suprised how interesting problems you can get when someone think they can just do if (a) and if (!a) as "normal".


    There are no such "systems" only bad programmers if they make FALSE to mean non-zero and TRUE to mean zero, just like writing a class where read() means write and write() means read. It will compile but won't work the way the user expects it to and will therefore be wrong.

    In C and C++, boolean expressions are true if non-zero and false if 0, so comparing to false is ok (albeit bad style but comparing to true is wrong because true could be 1, -1 or a bit-mask etc and it is not guaranteed that one true value is equal to another.

    Comparing a pointer to NULL (or 0) or a return value to 0 is another matter. It is probably good style here. It is bad style in my opinion to compare strings in C with a statement such as
    if ( !strcmp( str1, str2 ) )

    - because of the quirk of strcmp that it returns 0 if the strings are the same and non-zero if they are different (<0 or >0 according to ordering). Better to say
    if ( strcmp( str1, str2 ) == 0 )

    (note it won't compile if you put = 0 here as the return of strcmp is not an l-value)

    Note also that an overloaded operator == or != in C++ is not guaranteed to be defined both ways so

    if ( 0 != obj )

    is not guaranteed to be defined at all just because you can do

    if ( obj != 0 )


    Now for the original post, something strange I noticed was that the coder was doing a foreach loop and didn't use the loop object (match) which seems rather strange to me.

  • TonyP 2007-01-29 09:55
    In C#,

    if(someValue)

    and

    if(!someValue)

    looks better than

    if(someValue == true)

    and

    if(someValue == false)

    That's just me.
  • darwin 2007-01-29 14:36
    [quote user="Jackal von ÖRF"][quote user="EvanED"][quote user="htg"]However it is less CPU overhead than executing code in a try..catch statement (well, historically in Java, I don't know about now, or C#).[/quote]

    That depends on the implementation, and how often exceptions are thrown. I don't know how Java or C# does it, but it's possible (and I think at least sometimes done) to compile exceptions in such a way that if an exception isn't thrown there is NO overhead...

    The overhead of try-catch blocks, when not throwing exceptions, should be a problem only when the try-catch is inside a loop/hotspot. The overhead is in entering/exiting the try-catch block, and not in running code inside the block.

    Quoted from http://www.mortench.net/blog/2006/08/08/dos-and-donts-for-exception-handling-or-what-every-developer-should-know-about-the-implementation-of-exception-handling/
    "Specifically, the case of overhead of try-catch-finally constructions when no exceptions occur is difficult to get rid of by compiler & virtual-machine implementers. [--] Basically this is because something like a “linked list” has to be maintained internally by the compiler or VM each time the control flow enters or exits a try-catch-finally."[/quote]

    I'm not sure if that information is correct. It's possible that some JITs for Java compile code in a way that requires maintaining some overhead data structure when entering and exiting try/catch blocks, but in interpreted code this would not be necessary since the method has a table relating sections of the bytecode to catch blocks. As long as the JITted code could map offsets in the native code back to the bytecode it was compiled from, it could use this table, and thus would not have to maintain any further data structure.

    At least the Sun JVM on 32-bit Windows seems to do this. I haven't had a chance to try any other architecture yet. I created a class that adds up some numbers in a loop, parsing them all from Strings with Integer.parseInt() (but they're all good, so no exceptions will be thrown). It doesn't matter whether I have a try/catch block for NumberFormatException in the inner loop, the running time for one million iterations is the same.

    It would be interesting to hear if this actually is a problem on other JVM's, or other architectures.
  • Adnan 2007-02-01 00:32
    I am not that expert at it as some of you guys are but I can see why someone would want some functions to return an exception like that. Perhaps in situation of a network connection where you are remotely executing some function on the server and wanted to make sure that no exceptions were thrown.
  • asopytzv nfayrdx 2007-02-05 21:37
    pndeukab gnsz qseygox iugoprvt wkdalfoe ylni knfmjstyo
  • Joey 2008-09-22 09:10
    Hah I don't blame the guy, trying and catching it such a pain compared to just returning a success indicator of some kind.
  • Anon 2009-02-23 09:24
    AndrewB:
    Ever heard of readability?


    Absolutely. And I also know that "if (...)" and "while (...)" expect boolean expressions. Hint: Comparing a boolean variable to 'true'/'false' doesn't make it more boolean.

    I find "if (a && b)" quite readable. Quick: Tell me when which branch of the following conditional will be taken:

    if (! (a != true && b == !false))

    I wish the programmer had just written

    if (a || b)

    In everyday language, do you say "If it's true that I carry an umbrella, then it's not going to rain?" Just say what you mean: "If I carry an umbrella, it's not going to rain."

    "...== false" is a hint that the programmer never understood that Boolean is an algebra, and that he can simply write things like

    bool ok = ((0 < x) && (x < 10));

    Now if he didn't get _that_, what else did he miss?

    Of course, when dealing with _numbers_ instead of boolean, I'd insist on a comparison. A number or a pointer value is not boolean by concept, so I want to see

    if (u > 0) /* assuming unsigned u; */

    if (p != NULL) /* assuming p is a pointer */

    The C interpretation "zero is false, non-zero is true" is not obvious.
  • cindy 2010-12-21 09:08
  • Isikyus 2013-05-29 07:25
    This is probably obvious, but what about Java's Throwable.getCause()?

    Not that most people would be implementing that, of course...