• Also Me (unregistered) in reply to me
    me:
    I don't know why people are being so harsh. This is a well known, time proven algorithm. It was used extensively during the Salem witch trials.

    bool is_witch(victim) { witch = acquire_lock(victim); submerge(witch); sleep(3600); if (witch.is_dead()) return false; // not a witch; sorry return true; }

    Better:

    bool is_witch(victim) { witch = acquire_lock(victim); Duck quacky = new Duck(); if (witch.getWeight() != quacky.getWeight()) return false; // not a witch; sorry return true; }

  • (cs) in reply to szukuro

    This brings to mind an old quandry of mine. Should a File.Delete method return a FileNotFound error, or just take the credit and return success if the file wasn't there in the first place. I have to admit I have created plenty of code that steals credit for work that is already done when the method is called. Am I creating WTF fodder?

  • Alex (unregistered)

    enum {TRUE, FALSE, FILE_NOT_FOUND} - nuff said.

  • ComputerForumUser (unregistered)

    Actually, the real wtf is that they didn't just write:

    10 let private bool FileExists(path as char*) :=
    {
        try
            let FILE *F = File.OpenWrite(path);
            let int f := strlen(File.ToString(path));
            for int i := 1 to f;
                let char c := (i&3==0?'n':i&3==1?'a':i&3==2?'r':'f').IntValue().ToChar();
                fprintf(F, "%c", c);
            next i;
            fclose F;
        catch(ex as exception)
            ; do nothing
        end catch
        let FileExists := Boolean.FILE_NOT_FONDU;
    }
    
  • (cs) in reply to So.....
    So.....:
    What do you think TryParse does....

    Just checked, there isn't a single try catch in the TryParse method and the methods it calls

  • (cs) in reply to jfuex
    jfuex:
    This brings to mind an old quandry of mine. Should a File.Delete method return a FileNotFound error, or just take the credit and return success if the file wasn't there in the first place. I have to admit I have created plenty of code that steals credit for work that is already done when the method is called. Am I creating WTF fodder?

    Well you would expect that after calling the Delete function that the file doesn't exist anymore, so I would just return true if it never existed anyway.

  • devy (unregistered)

    HAHA, Im ashamed to say that I did something very similar when I first started using c#... Only not quite as bad as that.

    Some of that is still in production on at leat 2 big web sites that I worked on.

    Captch: goddamnsonofabitchstolemymonkeypaddleandspankedmewithit

  • (cs)

    Let me get this straight, the developer knew about the File object, but didn't bother to check what the "Exists" method does? How sad, especially with visual studio, where the names of all the methods pop up as you type....


    Free books, tutorials, and documents at http://www.BookGoldMine.com

  • Foo (unregistered) in reply to snoofle
    snoofle:
    ParkinT:
    A 'catch' that does nothing but return false!

    I think I will start using that in all my code; now I have a reason to USE try/catch! </sarcasm>

    On a side note, I don't mind catch blocks that do nothing, IF it's a very tiny narrowly constrained block of code, and there's a default value/action. For example, say you're reading some int from the environment:

       private final static int DEFAULT_VALUE_OF_X = 1024;
       int xEnvtVal = DEFAULT_VALUE_OF_X;
       try {
           xEnvtVal = Integer.parseInt(System.getProperties().getProperty("X"));
       } catch (Exception e) {
         // not set in envt or set-value is not an int: use default value
       }
    

    Of course, setting the default value in the exception might be more obvious, but I'm not (usually) that picky.

    One word: Bad.

    Exceptions should be used for exceptional conditions. You really should test to see if the value is defined and then take the appropriate action. If the value cannot be parsed to a number that exception should be handled correctly since that's a configuration problem. I'd still vote for even logging that you are using the default value as either a debug or an info to make life easier for the administrators.

    In any case, swallowing that exception is still a bad practice (especially since it's Exception and not something more specific). There are all sorts of problems that could occur with a supposedly set value (incorrect type, misspelling of the variable name, file not found, etc.).

  • Poppa Vein (unregistered) in reply to G-Unit
    Let me get this straight, the developer knew about the File object, but didn't bother to check what the "Exists" method does? How sad, especially with visual studio, where the names of all the methods pop up as you type....
    If the executing process doesn't have sufficient permissions to read the file, File.Exists() will return false even if the file does exist. See comment 120797.
  • FileNotFound (unregistered) in reply to me
    me:
    I don't know why people are being so harsh. This is a well known, time proven algorithm. It was used extensively during the Salem witch trials.

    bool is_witch(victim) { witch = acquire_lock(victim); submerge(witch); sleep(3600); if (witch.is_dead()) return false; // not a witch; sorry return true; }

    Nope. That should be: witch test_witch(victim) { witch = acquire_lock(victim); submerge(witch); sleep(3600); if (!witch.is_dead()) witch.burn_at_stake(); return witch; }

  • (cs) in reply to So.....
    So.....:
    benryves:
    snoofle:
    On a side note, I don't mind catch blocks that do nothing, *IF* it's a very tiny narrowly constrained block of code, and there's a default value/action.
    Don't even bother catching the exception object, then...
    int xEnvtVal = DEFAULT_VALUE_OF_X;
    try {
        xEnvtVal = Integer.parseInt(System.getProperties().getProperty("X"));
    } catch { }

    That said, it's still evil.

    int xEnvtVal;
    if (!int.TryParse(System.getProperties().getProperty("X"), out xEnvtVal)) {
        xEnvtVal = DEFAULT_VALUE_OF_X;
    }

    What do you think TryParse does....

    In C# TryParse does not just catch and swallow an exception, try using Reflector on MSCORLIB and you can examine the code.

    The main problem with using the Try/Catch technique rather than the TryParse method is catching exceptions is resource intensive and slow.

    Try it, write a little test app and you'll find in a good-case scenario, TryParse and Try/Catch perform about the same. However, in the bad-case scenario, TryParse performs faster than the good-case, while Try/Catch is several orders of magnitude slower....

    -Me

  • Frandsen (unregistered)

    Three things are certain: Death, taxes, and lost data. Guess which has occurred.

  • (cs) in reply to snoofle
    snoofle:
    On a side note, I don't mind catch blocks that do nothing, *IF* it's a very tiny narrowly constrained block of code, and there's a default value/action. For example, say you're reading some int from the environment:
       private final static int DEFAULT_VALUE_OF_X = 1024;
       int xEnvtVal = DEFAULT_VALUE_OF_X;
       try {
           xEnvtVal = Integer.parseInt(System.getProperties().getProperty("X"));
       } catch (Exception e) {
         // not set in envt or set-value is not an int: use default value
       }
    
    I mind it. It's still very bad coding. (So is catching java.lang.Exception, by the way.)

    Since your example looks for a system property, you could have done:

       private final static int DEFAULT_VALUE_OF_X = 1024;
       int xEnvtVal = Integer.getInteger("X", DEFAULT_VALUE_OF_X);
    

    No catching needed.

    Personally I'd go a step farther and put out a high-level log message (or maybe even throw a RuntimeException) for a badly formatted property. If someone went to the effort to set it, they will want to know why it's being ignored.

  • sluggo (unregistered)

    BOFH Programming... "You mean this file?"

  • VB++ guru (unregistered) in reply to Sven

    does VB.Net still exists?

  • Eternal Density (unregistered) in reply to VB++ guru
    VB++ guru:
    does VB.Net still exists?
    let's do a (destructive) check of that...

    captcha: smile (VB.NET: smile for the camera. boom ok, that wasn't a camera)

  • DeQuincey (unregistered) in reply to C Gomez
    C Gomez:
    So really, if you're just punching the clock, you aren't out ahead of the curve reading about things so you're ready when you need them.

    Your comment reminds me of the DBAs at my first company. These people had such a narrow focus, that they only understood database theory and their database environment. They had no clue how to use and no desire to learn how to use, the operating system installed on their desktops. (I agree that DBAs don't need to know much about their desktop OS. However, some understanding of it can only help them. Even if it's only to detect/fix/avoid simple problems.)

    I don't consider these types of people my peers. I don't even consider them to be true IT workers.

    IMO, if your curiosity isn't insatiable, you don't belong in IT.

    As you've mentioned, the problem is a narrow focus on one's paycheck.

    captcha: pinball ... "ouch"

  • Jonah (unregistered)

    As others have already noted, this function will return true unless it is unable to create or overwrite the file. This would normally be a permissions issue, but it's possible some sort of intermittent problem could cause an exception to be thrown, and the function to return false. Fortunately, a steady diet of WTFs has taught me how to deal with this sort of thing:

    private bool FileExists(string strPath)
    {
        try
        {
            File.WriteAllText(strPath, "narf");
            return true;
        }
        catch (Exception ex)
        {
            try
            {
                File.WriteAllText(strPath, "narf!");
                return true;
            }
            catch (Exception ex)
            {
                try
                {
                    File.WriteAllText(strPath, "narf!!");
                    return true;
                }
                catch { /* I think 3 tries is good enough */ }
            }
        }
        return false;
    }
  • Wim (unregistered) in reply to Roy
    Roy:
    Actually this looks way to stupid to be in an actual running environemt. Looks more like a joke to me.
    Ah, you're so charmingly naïve! I've seen plenty of code this bad in deployed systems. The programmer was probably paid by kLOC, or by number of bugs marked fixed, or something. Or just knew that he'd be on to another job before any of this crap had to be maintained.
  • (cs) in reply to FileNotFound
    FileNotFound:
    me:
    I don't know why people are being so harsh. This is a well known, time proven algorithm. It was used extensively during the Salem witch trials.

    ...

    Nope. That should be: witch test_witch(victim) { witch = acquire_lock(victim); submerge(witch); sleep(3600); if (!witch.is_dead()) witch.burn_at_stake(); return witch; }

    Thing is, you keep forgetting to release_lock(). Going to crash and burn later along the line ;)

  • BruteForce (unregistered) in reply to Also Me
    Also Me:
    me:
    I don't know why people are being so harsh. This is a well known, time proven algorithm. It was used extensively during the Salem witch trials.

    bool is_witch(victim) { witch = acquire_lock(victim); submerge(witch); sleep(3600); if (witch.is_dead()) return false; // not a witch; sorry return true; }

    Better:

    bool is_witch(victim) { witch = acquire_lock(victim); Duck quacky = new Duck(); if (witch.getWeight() != quacky.getWeight()) return false; // not a witch; sorry return true; }

    No quack

  • Blame (unregistered) in reply to C Gomez
    C Gomez:
    Roy:
    Actually this looks way to stupid to be in an actual running environemt. Looks more like a joke to me.

    It's not. Here's why.

    Many developers who are unfamiliar with Java or .NET have had to make the jump from VB or C++ because that's where their employer is taking them.

    Instead of taking the time to learn the new frameworks, and even explore them a little, they jump right in. And hey, we all have to get work done, so hmm, how can I get this done?

    This is what leads to this. For example, I saw littered throughout some code I was reviewing (C#) various ways to check if a string was empty instead of just comparing it to String.Empty. I saw another developer create all sorts of fancy state data to make sure some code was running on the UI thread instead of just testing InvokeRequired and then doing an Invoke to make sure it was.

    It's not a joke, its undereducation. There isn't an impetus from management to offer training, either. So really, if you're just punching the clock, you aren't out ahead of the curve reading about things so you're ready when you need them.

    WTF?

    I'm astounded by the stupidity of this comment. Are you seriously suggesting that if you learned to program in a different language it would seem reasonable to do this?

    You're fired!

  • (cs)

    That kind of test function brings this to mind:

    911 operator: Are you sure he's dead? *pause* *bang* Man: Now I'm sure.
  • LoneCoder (unregistered)

    How many users of that app have rung Symantec saying a new virus is spreading havoc in their filesystem?

  • Tom (unregistered)
  • Homser S (unregistered)

    FUN! ;-)))

  • (cs) in reply to Poppa Vein
    Poppa Vein:
    .NET System.IO.File.Exists (MS.NET 1.1) is a WTF anyway... From MSDN:

    "Returns true if the caller has the required permissions and path contains the name of an existing file; otherwise, false. If the caller does not have sufficient permissions to read the specified file, no exception is thrown and the method returns false regardless of the existence of path."

    That is, "the file may exist, but we're not going to tell ya".

    So maybe the original post isn't a WTF at all. Maybe the full algorithm was

    Test if file Exists. If the file doesn't exist, try writing something to it. If we can't write to it, it did exist after all.

    Alternatively, maybe Pinky did write the function.

  • (cs) in reply to Poppa Vein
    Poppa Vein:
    .NET System.IO.File.Exists (MS.NET 1.1) is a WTF anyway... From MSDN:

    "Returns true if the caller has the required permissions and path contains the name of an existing file; otherwise, false. If the caller does not have sufficient permissions to read the specified file, no exception is thrown and the method returns false regardless of the existence of path."

    That is, "the file may exist, but we're not going to tell ya".

    That looks perfectly sensible to me. If the user doesn't have sufficient permissions to read the file, good security says that the user shouldn't even know whether the file exists or not. It's kinda like when someone enters an invalid username or password; good security says you don't tell them which one was wrong. Bad security says "You entered the wrong username. There's no user named johndoe, but there is a johndont. Try that one instead."

  • Phill (unregistered) in reply to snoofle
    snoofle:
    ParkinT:
    A 'catch' that does nothing but return false!

    I think I will start using that in all my code; now I have a reason to USE try/catch! </sarcasm>

    On a side note, I don't mind catch blocks that do nothing, IF it's a very tiny narrowly constrained block of code, and there's a default value/action. For example, say you're reading some int from the environment:

       private final static int DEFAULT_VALUE_OF_X = 1024;
       int xEnvtVal = DEFAULT_VALUE_OF_X;
       try {
           xEnvtVal = Integer.parseInt(System.getProperties().getProperty("X"));
       } catch (Exception e) {
         // not set in envt or set-value is not an int: use default value
       }
    

    Of course, setting the default value in the exception might be more obvious, but I'm not (usually) that picky.

    No, no, no. That's always bad. If there is no TryParse or equivalent available, I would sometimes rely on this method but you should never write catch(Exception e)! What about catch(FormatException e) or catch(ParseException e) or catch(OverflowException e)! Just because it's a narrow block of code doesn't mean that Something Bad(tm) can't happen in that block of code and get swallowed, meaning that weird errors start your program because you've run out of memory (for example) and you don't know about it.

  • Phill (unregistered) in reply to Phill

    Arrgh! I hate not being able to edit posts. Please ignore all speling[sic] errors in the previous post!

  • wtf (unregistered) in reply to akatherder
    akatherder:
    The FileExists function should be named RuinFileIfItExists. Then if used properly, it is useful. Hopefully you would get a permissions error or at least a write protection error for any critical files, but you could still do a lot of damage.
    oooh you totally messed the comment up. you should've written "NerfFileIfItExists".
  • Dave C. (unregistered)

    Ha ha. Test to destruction -- on a file! (Er, in retrospect, it doesn't really take that much to do it.)

  • antred (unregistered) in reply to Poppa Vein
    Poppa Vein:
    .NET System.IO.File.Exists (MS.NET 1.1) is a WTF anyway... From MSDN:

    "Returns true if the caller has the required permissions and path contains the name of an existing file; otherwise, false. If the caller does not have sufficient permissions to read the specified file, no exception is thrown and the method returns false regardless of the existence of path."

    That is, "the file may exist, but we're not going to tell ya".

    Well, I guess the reasoning being that if you can't do squat with the file anyway then it might just as well not exist to you. I realize that this is not really adequate in all situations ... like when trying to create a file with the same name.

  • general failure (unregistered)

    unfortunately it is not a joke... I am an assembler programmer, in fact i am the "antivirus" guy, i do reverse engineering for viruses, helping my colleagues to create antivirus programs in my company, and i found plenty of examples of such a code.. I have a big collection of such things.... sad but true...

    "who is this general failure, and WTF is he doing in my computer?"...

  • Ralph Corderoy (unregistered)
    I wish I could remember who said that "back in the day, they had transaction safe databases: we called them file systems.

    You're probably thinking of ken: "We have persistent objects, they're called files". He was referring to the latest buzz-phrase of the time.

    http://en.wikipedia.org/wiki/Ken_Thompson http://en.wikiquote.org/wiki/Kenneth_Thompson

    -- Ralph.

  • Jake (unregistered) in reply to Roy

    Sadly, the joke is on you. I work for a large bank, and see this kind of "a comp sci intern wouldn't even code it" crap going to production on a daily basis...

    The problem is, in my company (which I doubt is alone) - over 1/2 the developers have never had even 1 course in computer science. They're "philosophy" majors who learned how to program on their own (and other non-technical majors).

    So, without learning the basics from the ground up, there's a lot of - "if it does what you expect it to do when you call in the function you currently call it from, it's good enough".

    Who cares what you call it...or what it does...or... My head is hurting just thinking about this. I'm glad my interview went well yesterday. I'll be out of the madness soon...

  • Lou (unregistered) in reply to Cyrus
    Cyrus:
    Narf? Oh man, my childhood memories are flooding back. What are we going to do tonight Brain?

    As a side story, simply opening the file and catching the error used to be faster than checking to see if it existed on old systems, don't know how that measures up now.

    Childhood memories? Boy Howdy do I feel old. I was already graduating college when narf/brain came out.......

    Geez!

    Still -- I like the idea, what if instead of 4 characters of gibberish, this had been real code inserted? :-)

    Captcha: Old School!

  • SproutMaster (unregistered)

    Just for fun, here's the same thing in VBA, I alwasys aim at One-Line Code where possible.

    But with no WTFs: boolCheckIt = IIf(Len(Dir("PathAndFileName")) > 0, True, False)

    Quite neat huh.

    Any one else know the same job in an other language with just One-Line Code.

  • Jfuex (unregistered) in reply to XIU

    That's my thought too. However, I have seen a lot of code in my time that threw an exception if a file didn't exist during a delete. Maybe it is just me, but useless error messages like "Unable to delete file. File Not found." are pretty frustrating.

  • woohoo (unregistered)

    ZORT!

    so, if "narf" was not the result of the usual "obfuscation tactics", we know that said developer obviously was so busy taking over the world that there simply wasn't any time to look up the proper functions...

    captcha: atari!!! well, I never... the reminescences do add up today, don't they...

  • thurstan (unregistered) in reply to Jfuex
    Jfuex:
    That's my thought too. However, I have seen a lot of code in my time that threw an exception if a file didn't exist during a delete. Maybe it is just me, but useless error messages like "Unable to delete file. File Not found." are pretty frustrating.

    Actually there are a number of uses for that sort of thing... it can often mean that another user/thread etc is still using a shared access file.

  • Harrow (unregistered)

    BRAIN: Pinky! Are you pondering what I'm pondering?

    PINKY: Well, I think so, Brain, but wouldn't that just destroy the data in the file if it does exist?

  • noogen (unregistered) in reply to Sven
    Sven:
    Anonymous:
    C Gomez:
    For example, I saw littered throughout some code I was reviewing (C#) various ways to check if a string was empty instead of just comparing it to String.Empty.

    OK, I have to pull you up on this. Officially, the best way is to check that the string's length is zero, as that is faster than comparing to String.Empty.

    Otherwise you've got a valid point, though.

    .Net 2.0 also offers the String.IsNullOrEmpty static method, which is equivalent to doing (str != null && str.Length > 0).

    And in VB.NET the compiler is smart enough to automatically replace comparisons to an empty string with something that's equivalent to that.

    Sorry, but I had to jump in because you guys did not really get the point of comparing str.Length instead of empty string.

    If you ever trace on string comparison before, you will find that two empty string does not necessarily equal to each other. Though string are immutable, they can still have different instances. This is why empty string are should not be reference compares (== or .Equals) but with .Length <= 0. Summary, it's possible that "" != string.Empty

  • S (unregistered) in reply to noogen
    noogen:
    Sorry, but I had to jump in because you guys did not really get the point of comparing str.Length instead of empty string.

    If you ever trace on string comparison before, you will find that two empty string does not necessarily equal to each other. Though string are immutable, they can still have different instances. This is why empty string are should not be reference compares (== or .Equals) but with .Length <= 0. Summary, it's possible that "" != string.Empty

    But since they're talking about .NET and in .NET the equality is not a pointer comparison but a real content comparison, they can be tested with ==. And naturally it's possible that in some environment String.Empty is not "" but in .NET it is.

    Also to the File.Exists() talk, as someone already said, it's a security thing that the program isn't told if a file it has no permissions exists or not. Otherwise you could brute force find all files on the machine and even get some information from the names.

  • y (unregistered) in reply to SomeCoder
    SomeCoder:
    Oh dear god. Please tell me this code is a joke. Please? This is just.... gah...

    And that testing for a witch code was pretty damn good :)

  • Anonymous (unregistered) in reply to Cyrus

    But Alex, if the monkey uses his tail for the mouse, how does he use the thumb buttons?

    :)

  • zdux (unregistered)

    lol dats f'ed

Leave a comment on “Fun with Files”

Log In or post as a guest

Replying to comment #:

« Return to Article