• Betta Glurpse (unregistered) in reply to Anon
    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 (unregistered)

    Hehe, this is a really good laugh.

  • (cs) in reply to Fredric
    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 (unregistered)

    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();
      }
    }
    
  • (cs) in reply to htg
    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 (unregistered) in reply to Cyrus
    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.

  • (cs) in reply to Fredric
    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 (unregistered)

    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).

  • (cs) in reply to snoofle
    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 (unregistered) in reply to EvanED
    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 (unregistered) in reply to Jax

    Sorry my formatting was all of:

    class Exception

    |

    |--- class SystemException

    -----|

    -----|--- class OutOfMemoryException

  • (cs) in reply to Eam
    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.

  • (cs) in reply to Smudge
    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; }
  • (cs) in reply to snoofle
    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

  • (cs) in reply to Jax
    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

  • (cs)

    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 (unregistered) in reply to willy
    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 (unregistered)

    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.

  • (cs) in reply to Jax
    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...

  • (cs) in reply to gwenhwyfaer
    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 (unregistered) in reply to Andrew Bell

    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" :-)

  • (cs) in reply to gwenhwyfaer
    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).

  • (cs)
    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);
    
  • (cs) in reply to Smudge
    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 (unregistered)

    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 (unregistered) in reply to snoofle
    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 (unregistered)

    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.

  • (cs) in reply to EvanED
    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 (unregistered)

    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 (unregistered) in reply to willy
    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 (unregistered) in reply to htg
    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 (unregistered) in reply to htg
    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 (unregistered) in reply to EvanED
    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 (unregistered) in reply to gwenhwyfaer
    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?

  • (cs) in reply to al
    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 (unregistered) in reply to Hans
    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 (unregistered) in reply to htg

    Actually, yours isn't stellar.

    my %t ...

  • ehren (unregistered) in reply to Kemp

    "Do you have to turn everything into a double-entendre?"

    "No..."

    later

    "I'd like to double [i]her[\i] entendre!"

  • darwin (unregistered) in reply to Andrew Bell
    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 (unregistered)

    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.

  • (cs) in reply to AndrewB
    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.

  • (cs) in reply to Betta Glurpse
    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 (unregistered)

    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 (unregistered)

    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?

  • (cs) in reply to htg
    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 (unregistered) in reply to Smudge
    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 (unregistered)

    %%SomeWord%% -> knowing 4% of regex functionnalities ?

  • Betta Glurpse (unregistered)

    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 (unregistered)

    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 (unregistered) in reply to verisimilidude
    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.

Leave a comment on “Catch and Release”

Log In or post as a guest

Replying to comment #:

« Return to Article