• (cs)

    Contrary to what you might think, there are instances of language implementations that consider a bunch 'o spaces to be the same as a null string.

    Back in oh around 1990, i had the displeasure of having to use Metaware's Pascal on Interactive IX/386 UNIX. Not only did it consider "andy " to be equal to "andy" (grr) but the developers (sic) of the compiler explained that it was there for PL/1 programmers (pounds head against wall). So I guess a bunch 'o spaces would compare equal to "".

    So, had to "dis" (assemble) the offending RTL function, and re-assemble it (AT+T syntax of course) without any manuals.

    (That and a length word for "Borland/UCSD" style strings game me a lot of unentertaining unsleep - porting a general ledger program from Borland).

    Your consultant is clearly in need of deeply improving electroshock therapy..

  • (cs)

    I could actually understand if the code was actually supposed to count a bunch of whitespace as an empty string. If it is being used for input validation for a form, it makes sense. But if thats the case, the function was poorly named.

  • Peter Harrison (unregistered)

    Um, first of all making the Parameter a String would eliminate the need for a check at all. If you need to check for whether its a String do it before the function.

  • wtfcomments (unregistered) in reply to hanno

    wrong.

    .Equals doesn't existt. String.Empty doesn't exist.

  • wtfcomments (unregistered) in reply to AndrewB
    AndrewB:
    "".equals(whatever)

    is technically not optimal because it unnecessarily wastes processor time constructing a string object ("") when one may very well already be constructed for us.

    Don't reinvent the wheel!

    String.Empty.equals(whatever)

    Also, here is the solution to the original solution

    public boolean isEmptyStringOhAndUseThisFunctionAndNotIsEmptyStringBecauseItIsBroken(Object obj) { return !isEmptyString(obj); }

    err.. ever heard of String intern?

    String.Empty.equals(whatever) - doesn't exist.

  • wtfcomments (unregistered) in reply to Chuggid
    Chuggid:
    return (obj instanceof String) && obj.toString().trim().length() == 0;

    now, why having already ascertaining that the object is a String, would you toString() it? Furthermore, why trim it?

  • wtfcomments (unregistered) in reply to TSK
    TSK:
    Chuggid:
    TSK:
    public boolean isEmptyString(CharSequence string) { return "".equals(string); }
    Doesn't handle the case of passing in, say, an Integer, which I take it the method is supposed to.

    I suppose you could do this:

    return String.valueOf(obj).equals("");

    ...and make the assumption that if an incoming Object's toString() method results in "" you should count it as an empty string too.

    You cannot enter an Integer because the method needs a CharSequence, meaning that you will get a compile error. I would even go further and don't allow a null at all:

    (Final)

    public boolean isEmptyString(CharSequence cs) { if (cs == null) throw new IllegalArgumentException("cs must not be null !"); return "".equals(cs.toString); }

    null don't make any sense at all for the method, so simply tell the programmer in no uncertain terms that he has done an error.

    yeah but you've changed the method signature

  • Jon (unregistered) in reply to woohoo
    woohoo:
    this can easily be verified by the following: if (new String("") == new String("")) ... yields 'false' (because there are 2 distinct objects) if ("" == "") ... yields 'true', because you effectively compare the internalized instance to itself.
    Since the equality operator is overloaded for C# strings, you'd probably want String.ReferenceEquals("", "") (and, yes, it still returns true).
  • brendan (unregistered)

    The best way of doing this would be:

    public static boolean isEmptyString( String obj ){ return ((s != NULL) && (s.trim().length() == 0)); }

    Also this isn't a real wtf. It could be used in a lot of situations (for example reading/validating a file).

  • (cs) in reply to brendan
    brendan:
    The best way of doing this would be:

    public static boolean isEmptyString( String obj ){ return ((s != NULL) && (s.trim().length() == 0)); }

    Also this isn't a real wtf. It could be used in a lot of situations (for example reading/validating a file).

    Hello, it's me again. This time with my "cruel pixie" cap fixed firmly on my head.

    Alex, I'm curious about your "non-WTF" job service. Do you warn potential employers that people who claim that code like this "could be used in a lot of situations" to run, not walk, but run away as fast as they can? Or do you simply suggest that they browse the website for ambulatory disaster areas waiting to happen?

    Just wondering. It's a value-added sort of thing, really.

  • Sven Hoek (unregistered) in reply to Erwin

    // Big Boss programmer tells me that I need to add // an isNotEmptyString function to compliment isEmptyString.

    define IS_EMPTY_STRING 1;

    public static boolean isNotEmptyString( Object obj ) { if (obj != null) { if (isEmptyString (obj)) { return false; } else { return !isEmptyString(obj); } } else { // I dont understand why, but without this part, // program sometimes crashes with a recursion error ??? if (obj == null) {

         return IS_EMPTY_STRING;
    
         // TODO: Homework tonight - lookup 'recursion error'
         // hint - maybe its something to do with NULL objects ?
      }
    

    } }

    // which allows to to now simplify the existing code

    public static boolean isEmptyString( Object obj ) { if ( obj == null ) return (!isNotEmptyString(obj));

      if ( obj instanceof String )
      {
          /* a bunch of spaces is not an empty string, apparently */
    
          // boolean isSpace = checkForSpaces (obj);   // - dont need this anymore
    
          boolean isJustSpaces = false;
          boolean isSpace = true;
    
          for (int i = 0; i < ((String)obj).length(); i++) {
             String tempstring = (String) obj;
             if (tempstring.length() > 0 && IS_EMPTY_STRING) {
                if (tempstring[i] == ' ') {
                   isSpace = true;
                } else {
                   isSpace = false;
                   break;  // contains something other than a space,
                           // no need to check any further !!
                }
             }
          }
          if (isSpace) {
             isJustSpaces = IS_EMPTY_STRING;
    
             // We now know whether the string is just
             // empty spaces or not, as opposed to being
             // a really empty string.
    
             // Clever ;)
    
             // I have grown as a programmer today
          }
    
          
          if ( ((String)obj).length() == 0 )
              return ((int)false * IS_EMPTY_STRING);
      }
    
      return (!isNotEmptyString(obj) == IS_EMPTY_STRING);
    

    }

    // Do we still need this function ? public static boolean checkForSpaces (String str) {

    if (str.Equals (String(' ')) || str.Equals (String(' ')) || str.Equals (String(' ')) || str.Equals (String(' ')) || str.Equals (String(' ')) || str.Equals (String(' ')) || str.Equals (String(' ')) || str.Equals (String(' ')) || str.Equals (String(' '))) // That should be heaps enough to test for {
    return true; } return false;

    }

    /* TODO

    • this program still crashes sometimes with a 'recursion error' .. like when obj is NOT a string.

    • So add additional helper functions for each type of object that we can think of, and make it return true or false, depending on whether it is sensible for that type of object to be an empty string or not.

    eg: public static boolean isEmptyStringForIntegerType (Integer obj) { return true; }

    I feel like I am really starting to pick up this whole computer programming thing - its not too hard once you grasp the basics. Once your programs start looking real complicated, and check every possible little thing, then you KNOW that you are on the right track :)

    */

  • !Z (unregistered)

    The comments are much more wtf'ish than the code.

    The poor guy just got true and false mixed up - done that plenty of times myself (without any further context, we can assume he wants a null or non-string object to be treated as an empty string). That both versions are logically identical (except for treating spaces as significant) is the original 'wtf', but somehow it's been blown rather out of proportion in the comments.

    As an aside, If Java (and c-hash more-so) have such a large library of trivial functions that it takes forever to master them, i'm not sure it makes them better than simpler languages that do not.

  • Ron Pakston (unregistered) in reply to !Z
    <sigh/>

    Remember the days when TDWTF was not a competition to see who could come up with the best solution ?

    We all know how to fix the issue......now we have little whipper snappers posting absolute crap up and actually think we want a solution from them.

  • Booger (unregistered) in reply to sriram

    mmmm, yeah.. no, .NET does not use typeOf. C# uses typeOf. .NET uses Object.GetType().

  • (cs)

    To the people recommending the use of String.IsNullOrEmpty be wary of the evil IsNullOrEmpty bug. If you use it in a loop it will throw a NullReferenceException for no reason:

    		static void test(string x)
    		{
    			for (int j = 0; j < 10; j++)
    			{
    				if (String.IsNullOrEmpty(x))
    				{
    					//TODO:
    				}
    			}
    		}
    

    What's real fun is that it will only throw the exception if it's in release mode and the IDE is NOT used to run the program. I let you imagine the fun of trying to find the cause of a mysterious crash that you can not replicate...

    The kicker is that even though the bug has been known by microsoft since at least april 2006 it's still not fixed and won't be fixed until the next version of visual studio (aka orcas). Of course it will never be fixed in the current version and you'll have to pay for the new version to have the bug fixed.

    see : http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=113102

  • (cs)

    In C++

    template < typename T > bool isEmptyString( const T& t )
    {
       return false;
    }
    
    // overload for std::string
    inline bool isEmptyString( const std::string & s )
    {
       return s.empty();
    }
    
    // overload for const char *
    inline bool isEmptyString( const char * s )
    {
       return s && (*s == '\0');
    }
    

    Might be useful in meta-programming (templates) where you don't know what type you have.

  • TheDoom (unregistered) in reply to Earl Purple

    Yanks eh?

  • Maxi TB (unregistered)

    In .NET you just do a simple:

    return (value!="") & (value!=null);

    Nothing more is required.

  • cthulhu (unregistered)

    This WTF is BS. It is too absurd to be genuine. IMO the long story about consultants shows that the author knows full well what it takes to get a WTF put on the front page.

  • cthulhu (unregistered) in reply to Ron Pakston
    Ron Pakston:
    <sigh/>

    Remember the days when TDWTF was not a competition to see who could come up with the best solution ?

    We all know how to fix the issue......now we have little whipper snappers posting absolute crap up and actually think we want a solution from them.

    Remember the good old days when the internet was just a series of tubes?

    kind of know what you mean though

  • sigh (unregistered) in reply to Araqnid

    The real WTF here is that there are 120 comments discussing this screwed-up validation method.

  • (cs) in reply to !Z
    !Z:
    The comments are much more wtf'ish than the code.

    The poor guy just got true and false mixed up - done that plenty of times myself (without any further context, we can assume he wants a null or non-string object to be treated as an empty string). That both versions are logically identical (except for treating spaces as significant) is the original 'wtf', but somehow it's been blown rather out of proportion in the comments.

    As an aside, If Java (and c-hash more-so) have such a large library of trivial functions that it takes forever to master them, i'm not sure it makes them better than simpler languages that do not.

    An aside? Hardly. Language wars tend to revolve around irrelevances such as syntax, efficiency and optimisation. Quite a lot of the comments seen in TDWTF are along the lines of "it just looks ugly to me. Why don't you use <insert silver bullet here/>?"

    Now, I happen to be a C++ programmer by choice. There are good and bad things about the language. (I'm currently being forced to program in C as though it were C++, which certainly makes you appreciate the good things.) I've programmed in Perl, I've programmed in Python ... I'd even happily program in Java and C#.

    Except.

    I submit that all meaningful software is about choice. The problem I have with Java, C# and, for that matter, Visual Basic, is that someone has taken the choice away from you. Libraries do not a language make, nor should they be any more tightly coupled than, say, a linker. (I'd argue that there's a better case for the linker to be tightly coupled.)

    It's purely a practical matter. Anyone who has tried socket programming in MFC would understand this ... at some stage, even a minimal library will get frustrating, or not do what you want it to do, or at least in a way that you can understand properly.

    What you want is standards, and drop-in libraries. Curiously, Perl, with no standards to speak of, does quite well here. Java and C# suck at it -- and I'm not complaining about the language; I'm complaining about the environment. Several experienced developers on this site appear to agree with me. In my Hmbl Opn, someone fresh out of college doesn't stand a chance, unless they are in the top 10% of programmers -- which is precisely the 10% that these monolithic monstrosities are not supposed to reach, because "they do all the hard work for you."

    No they don't.

    </rant>
  • AdT (unregistered) in reply to rioshin
    rioshin:
    See the method declaration? It expects a CharSequence, and thus the method does not, repeat not, accept an integer to be passed in.

    Why don't you tell this the guy I replied to, you freak? I was not the one to bring up the discussion about integers, and you'd have noticed this if you were able to outsmart my doormat.

    I was merely commenting on the idea that "".equals(x) needs special-casing if x is an Integer. If type constraints indeed prevent x from being an Integer, this does not invalidate my argument in any way.

  • brendan (unregistered) in reply to real_aardvark
    real_aardvark:
    brendan:
    The best way of doing this would be:

    public static boolean isEmptyString( String obj ){ return ((s != NULL) && (s.trim().length() == 0)); }

    Also this isn't a real wtf. It could be used in a lot of situations (for example reading/validating a file).

    Hello, it's me again. This time with my "cruel pixie" cap fixed firmly on my head.

    Alex, I'm curious about your "non-WTF" job service. Do you warn potential employers that people who claim that code like this "could be used in a lot of situations" to run, not walk, but run away as fast as they can? Or do you simply suggest that they browse the website for ambulatory disaster areas waiting to happen?

    Just wondering. It's a value-added sort of thing, really.

    You really don't think that this code could be used at all. WTF!!!

    So you have never checked whether a required field (includes forms, configuration files,input files (for example testing whether a xml document is well formed), fields in a file and user/network input) was empty or skipped an empty line in a file (with a bit of string manipulation, you could also skip lines that contain only comments). WTF!!!. How did you get a job in programming (if you have a job, or even keep the job).

  • woohoo (unregistered) in reply to Jon
    Jon:
    woohoo:
    this can easily be verified by the following: if (new String("") == new String("")) ... yields 'false' (because there are 2 distinct objects) if ("" == "") ... yields 'true', because you effectively compare the internalized instance to itself.
    Since the equality operator is overloaded for C# strings, you'd probably want String.ReferenceEquals("", "") (and, yes, it still returns true).

    Not really, because I was talking of Java ;o)

    But still the same holds true for both languages regarding interned string literals (or explicitely interned strings for that matter, though I'm not sure if you can do this in C#).

    captch: ninjas ;o)

  • the_real_tel (unregistered) in reply to AdT
    I was merely commenting on the idea that "".equals(x) needs special-casing if x is an Integer. If type constraints indeed prevent x from being an Integer, this does not invalidate my argument in any way.
    See where you used the phrase "needs special-casing"? Utter nonsense.
    "".equals(x)
    is guaranteed by contract to accept an Integer argument, and will return false:

    http://java.sun.com/j2se/1.3/docs/api/java/lang/String.html#equals(java.lang.Object)

    ... unless you're additionally specifying that the method under scutiny should return true for Integer arguments, in which case, yes, it needs a special case. But you didn't say that.

    I think you are a special case though, if that's any consolation.

  • David (unregistered) in reply to hanno
    ((String)obj).Equals( String.Empty)

    Noooo! Reverse the order of the comparison. Always call the test function on the constant, so you don't randomly nullpointer on a bad input variable.

  • (cs) in reply to brendan
    brendan:
    real_aardvark:
    brendan:
    The best way of doing this would be:

    public static boolean isEmptyString( String obj ){ return ((s != NULL) && (s.trim().length() == 0)); }

    Also this isn't a real wtf. It could be used in a lot of situations (for example reading/validating a file).

    Hello, it's me again. This time with my "cruel pixie" cap fixed firmly on my head.

    Alex, I'm curious about your "non-WTF" job service. Do you warn potential employers that people who claim that code like this "could be used in a lot of situations" to run, not walk, but run away as fast as they can? Or do you simply suggest that they browse the website for ambulatory disaster areas waiting to happen?

    Just wondering. It's a value-added sort of thing, really.

    You know, I have no idea how I got a job in programming in the first place. I certainly have no idea why I'm still in the business twenty years on, because, to be frank, it sickens me.

    Far too many project managers. Far too much politics. Far too little actual development.

    But, Brendie baby, should you ever want to escape from your current hell-hole of "it works, why change it?" may I suggest that you examine the previous 140-ish postings, which describe in painstaking detail why the first version of the code is an abortion, and the second version is akin to an abortion eating its own twin.

    I'd love to spend more time having an erudite discussion with you on the subject of the original code, but, let's face it, you're a moron. And I have better things to do.

    Like go back over the last twenty years:

    brendan:
    You really don't think that this code could be used at all. WTF!!!So you have never checked whether a required field (includes forms, configuration files,input files (for example testing whether a xml document is well formed), fields in a file and user/network input) was empty or skipped an empty line in a file (with a bit of string manipulation, you could also skip lines that contain only comments). WTF!!!.

    How did you get a job in programming (if you have a job, or even keep the job).

    Nah, validation ain't in my job description. I tried that with Fortran 77, and it was too difficult. Nowadays I just earn my crust ensuring that useless little farts like you get fired.

    Much more satisfying.

    And no: I really don't think this code could be used at all. I have no idea what the requirements/functional spec looked like, but it's hard to imagine this implementation being even vaguely adequate. And it's at such a low level (and conflicting with various bog-standard library calls) that it can only cause confusion, if not disaster.

    A tiny bit of career advice, Brendan, from one who has been there:

    Learn to unit test low-level functions.

    That, or become a project manager.

    Res ipsa loquitur.

  • no longer barfing on real_aardvark (unregistered) in reply to gwenhwyfaer

    per earlier...

    The real WTF are companies that hire pretentious asses who make your work life a living hell, and have no ppl skills whatsoever.
    

    I'm getting a strong sense that for you, "people skills" = "never making me feel bad" - if that's the case, don't ever expect to do anything critical... or even useful. It's not that you'll screw it up, necessarily; but that if you have, you'll neither believe it nor trust anyone to convince you of it - and that's dangerous, as this place illustrates all too regularly.

    Not being unnecessarily cruel isn't the issue here; I'm all in favour of gentleness myself (I've been referred to as "the nicest person in the company" before, but I'm not sure that was a good thing) - but sometimes someone is just wrong, and it does nobody any good to pussyfoot around that.

    gah... sorry about that.. What you say is very true. I've worked with people in the past who just couldn't seem to figure it out, period. Couldn't use the tools at their disposal to improve, to move forward.. But perhaps it was just a phase, how am I to know? But you are right, you have to make a decision when it affects the performance of the company in a negative way over a period of time where some reasonable measure of success should have been garunteed.

    Pussyfooting can cost ALOT of money. :|

    PS: sry to real_aardvark. Sometimes I just tend to think there are those out there who just jump to conclusions too quickly. The Daily WTF, atleast to me, seems like a telephone game at times. Most of it is hilarious, I enjoy it, don't get me wrong... But other times, it's "John Doe worked with John Smith and boy... he wrote some crap code!" and who really knows what happened for sure, the story is only being portrayed by John Doe, so I take it with a grain of salt.

  • now barfing on myself (unregistered) in reply to no longer barfing on real_aardvark
    no longer barfing on real_aardvark:

    gah... sorry about that.. What you say is very true. I've worked with people in the past who just couldn't seem to figure it out, period. Couldn't use the tools at their disposal [...]

    Doh, like using quotes...

  • (cs) in reply to now barfing on myself
    now barfing on myself:
    no longer barfing on real_aardvark:

    gah... sorry about that.. What you say is very true. I've worked with people in the past who just couldn't seem to figure it out, period. Couldn't use the tools at their disposal [...]

    Doh, like using quotes...

    No worries, mate.

    (Always assuming that you're the same person.)

    I really should go back and apologise about linked lists, and not reading the post properly, and stuff ... but I just can't be bothered.

    Blogs are ephemeral, you know? Just because I use strongly-worded and generally annoying language doesn't mean I'm really that way.

    Now, all I have to do is to persuade the parole board of that...

  • Daniel M (unregistered) in reply to AndrewB

    Maybe you should read 'The Complicator's Gloves' : http://thedailywtf.com/Articles/The_Complicator's_Gloves.aspx

  • Morris (unregistered) in reply to Monkeyget
    Monkeyget:
    http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=113102

    From the developers that need no introduction:

    Microsoft:
    Visual Studio and .NET Framework Feedback Workarounds 113102. Null Exemption caused by JIt optimisation around String.IsNullOrEmpty A simple console application built as a release build with optimisations on will crash with a null reference exception caused by bad JIT optimisations around a call to String.IsNullOrEmpty inside a loop construct. Note the application must be run outside the IDE for this to be observed. Closed feedback entered 4/3/2006 by bill_mcc Entered by TAG on 6/25/2006 Create own IsNullOrEmpty method and mark it with NoInlining attribute:
    [MethodImpl(MethodImplOptions.NoInlining)]
    public static bool IsNullOrEmpty(string value)
    {
    if (value != null) {
         return value.Length==0;
    }
    return true;
    }
    
  • Orhun Jack (unregistered)

    Girls, have fun, not boys

  • Moppuy Appy (unregistered)

    My cap kills my brain

  • knwtdalh msdfxhy (unregistered)

    wvsh ajgmnqeob cekotrwsb lrmxs kmgfzoiy bpyguatik kgoebi

  • saunie (unregistered)

    want free sample of hydrocodone

  • saunie (unregistered)

    want free sample of loratab

  • HOly Spam (unregistered)

    Holy Spammo batman! Validating Nothing!

  • (cs)

    God, look at all the spam! :o

  • biojae (unregistered)

    if(obj != null && obj.toString().length() != 0) return true; return false;

  • captain p.e.n.i.s (unregistered) in reply to Erwin
    Erwin:
    It's just a matter of the wrong function name, in _both_ cases.

    It should have been isNotEmptyString, since they both return false when the string length is zero. (i.e. when the string is empty).

    The matter of the whitespace is good in both cases; since the method isn't documented, nobody can tell what is exactly meant by "empty" so both implementations are correct.

    So the real WTF is that the second developer didn't catch on to the real bug, being the name of the method.

    well... what about this? isEmptyString boolean (String s){ return s.equals(""); }

    one wants to test a String, doesn't one? so test for a String and not an object(which is an object, but... u know...). otherwise, the method has to have another name. or just use a wrapperClass to test everything that could be empty. but on the other hand, these tests are built-in-functions.

    or use a list:

    ArrayList<StringClassFromNoobDeveloper, Boolean> als = new ArrayList<String, Boolean>(); als.add("", true); als.add("i am horny", false); Iterator<StringClassFromNoobDeveloper, Boolean> its = als.iterator(); while(its.hasNext()){ System.out.println(its.next().getEmptynessOfCurrentString()) }

    not that is wtf! i love you!

  • captain p.e.n.i.s (unregistered) in reply to Araqnid

    well... what about this? isEmptyString boolean (String s){ return s.equals(""); }

    one wants to test a String, doesn't one? so test for a String and not an object(which is an object, but... u know...). otherwise, the method has to have another name. or just use a wrapperClass to test everything that could be empty. but on the other hand, these tests are built-in-functions.

    or use a list:

    ArrayList<StringClassFromNoobDeveloper, Boolean> als = new ArrayList<String, Boolean>(); als.add("", true); als.add("i am horny", false); Iterator<StringClassFromNoobDeveloper, Boolean> its = als.iterator(); while(its.hasNext()){ System.out.println(its.next().getEmptynessOfCurrentString()) }

    not that is wtf! i love you!

  • hornyatkoSep (unregistered)

    Hello.

  • Douglastab (unregistered)

    pharmacie en ligne france fiable https://kamagraenligne.shop/# п»їpharmacie en ligne france

Leave a comment on “Validating Nothing”

Log In or post as a guest

Replying to comment #:

« Return to Article