• (cs) in reply to Anonymous
    Anonymous:
    Trial by exception is bad enough - there are almost always ways to check for validity without relying on exception handling - but catching a top-level System.Exception when you're specifically looking for a FormatException is utterly retarded. The JVM could throw any number of internal exceptions (OutOfMemoryException for example) and this handler would pick them all up, even though it has no way of handling them and will actually misinterpret the results, thinking it's a FormatException when it could be something different.

    This code offends me.

    This is Java, Not C#. In Java, Throwable is top of the exception hierarchy, Exception is not a super class of Error, which is thrown when OutOfMemoryError occurs, and most other spontaneous exceptions.

    With that being said, in Java Integer is the c# equivalent of nullable int (int?), this method will incorrectly catch NullPointerException as log it as NumberFormatException.

    In reality, there are ways to do insert this code post compilation, or adjust runtime to do this.

  • Mike K (unregistered)

    Let us remember: outsourcing is never about quality of code; it's about money. Rookies (the people doing outsourcing coding) work cheap; experienced, competent coders cost real money, because they know what they are doing.

    One's IT infrastructure is too precious to outsource. But what do I know: I'm only a 30+ year IT veteran.

    MK

  • (cs) in reply to snoofle
    snoofle:
    sarge:
    Problem is a lot of WTFers out there would consider this as good code - why, it's got logging like a proper enterprise app!

    Anyone else noticed the mysterious methodName variable at the top? Has to be a static member is it's a static method. Hope this isn't multi-threaded code.

    Captcha: consequat - almost inconsequential?

    Erm, why? Do your methods change names while running? (assuming it's not changed for each method)

    Presumably is is changed for each method, otherwise the isValidString method is being logged as isValidInteger.

  • Fred (unregistered)
    public static boolean isUniverseStillDeterministic(Integer number) {
            try {
                Integer.parseInt(number.toString());
            } catch(Exception ex) {
                return false; 
            }
            return true;      
        }
    

    You're going to want to call this about 100 times a second, because if the Universe ever stops being deterministic you'll want to know right away that your calculations and logic are no longer reliable.

    Where it really gets interesting, then, is the code that calls isUniverseStillDeterministic. What are you going to do when you get a false? Better yet, how do you test that branch in your code? And if it does happen, you better log as much detail as possible to help unravel some of the fundamental problems of quantum mechanics.

  • Andreas (unregistered) in reply to Fred
    Fred:
    You're going to want to call this about 100 times a second, because if the Universe ever stops being deterministic you'll want to know right away that your calculations and logic are no longer reliable.
    I think, the universe did already stop being reliable: http://gasbanditry.com/twg163/pictures/Demotivational%20Posters/bug-report-for-god.jpg I guess, there was no unit test for this kind of situation...
  • God (unregistered) in reply to Andreas
  • Greg (unregistered)

    This would have been a valuable function if those Java jerks hadn't made the Integer class final. If you wrote a class like this:

    public class Aardvark extends Integer {
      public String toString() {
        return "aardvark!";
      }
    
      public static int parseInt(String str) {
        if("aardvark!".equals(str)) {
          return 1;
        } else {
          return 0;
        }
      }
    }
    

    ... this method would catch it. And log the details effectively except for eating the stack trace and not letting you know where or why it failed. Awesome.

  • (cs) in reply to sarge
    sarge:
    Anyone else noticed the mysterious methodName variable at the top? Has to be a static member is it's a static method. Hope this isn't multi-threaded code.

    People who are new to programming often don't entirely grok the concept of using a literal value directly in an expression of some kind; you'll see them constantly creating useless variables because they don't understand that literal values can be used outside of assignment operations. Such people also have trouble with using the return value of an expression or method call directly in an expression, without assigning it to a variable first.

    This is particularly common with students learning Java with no prior programming experience, which is not a slight against the language itself, but more against the way it is taught in American universities.

  • (cs) in reply to Andreas
    Andreas:
    We had the same experience with our CMMI Level 5 offshore-team. These guys had great processes that forced them to write
    if (a == b){
      return "something";
    }
    return "soemthingElse";
    
    instead of
    if (a == b){
      return "something";
    } else {
      return "soemthingElse";
    }
    

    The default config of some IDE (maybe Visual Studio) gives you warnings for the second code-block because it thinks you don't have a guaranteed return condition.

  • JV (unregistered) in reply to frits
    frits:
    sarge:
    Problem is a lot of WTFers out there would consider this as good code - why, it's got logging like a proper enterprise app!

    Anyone else noticed the mysterious methodName variable at the top? Has to be a static member is it's a static method. Hope this isn't multi-threaded code.

    They should have used annotations (in C#-ese, attributes) and reflection to avoid that ;).

    Logging every function call is not enterprisey enough. They should have converted the integer to XML and back to as a validation test.

  • Your Name (unregistered)

    OK, my guess is that whatever IDE they were using was generating method templates for them that included all of the logging, methodName, and other general crap.

    Is anyone familiar enough with CMMI to know whether all of this logging is "mandatory"? I worked for an organization that was working towards their certification, but that was 10+ years ago and I purged all that from my brain.

  • aidenr (unregistered) in reply to toshir0

    I read recently that Korean Air Lines found that they had a safety problem stemming from cockpit communications between co-pilot and pilot. Apparently the polite words in Korean slowed down certain kinds of problem reports, which can be catastrophic in airlines. Switching to English, with its lack of inherent power considerations, brought their safety record into line with international standards.

    I suspect that the offshore development enterprises have a similar issue: being cheap, they hire lots of moderate talent. Having large teams, they hire lots of management. Having lots of managers, they implement CMMI-style processes. Given a soulless process, pointless bureaucracy, arcane specs, and a huge team of co-workers, I suspect that the individuals fail to take pride of ownership. It's the only explanation I have for the amazingly bad code quality.

  • fyfex (unregistered)

    They should have used

    try {
        Integer.parseInt(String.valueOf(number));
    } catch(Exception ex) {
        ...
    }
    

    to catch the null as an NFE...

  • mypalmike (unregistered)

    I like the fact that this can return false:

    public static boolean equalToSelf(float n) {
       return n == n;
    }
    
  • ioccc (unregistered) in reply to SR

    hehehe, I would not be too surprised if the management at the outsourcing company had something in place where developers were rewarded on defects per KLOC (kilo-lines of code). Solution, write your code unnecessarily long and add redundant methods.

  • ioccc (unregistered) in reply to Thomas

    Hmm, I think I have an improvement to the code:

    public static boolean isValidNumber(Integer number) { methodName = "isValidNumber"; Logger logger = LoggingHelper.getLogger(LOGGER); logger.entering (CLASS, methodName);

        // parse this number. If you get an NFE, then its 
        // not valid, return false
        try {
            Integer.parseInt(number.toString());
        } catch(NumberFormatException nfe) {
            logger.fine(methodName + " returns false");
            logger.fine("Number Format Exception when parsing");
            
            return false; 
        } catch(NullPointerException npe) {
            logger.fine(methodName + " returns false");
            logger.fine("Null Pointer Exception when parsing");
            return false;
        } catch(Exception ex) {
            logger.fine(methodName + " returns false");
            logger.fine("Unexpected exception when parsing");
            return false;
        }
    
        logger.fine(methodName + " returns true");
        logger.exiting(CLASS, methodName); 
        
        return true;      
    }
    

    :)

  • ioccc (unregistered) in reply to Severity One

    This totally made my day. I'm just glad I wasn't drinking anything when I read your post. Thanks.

  • Anonymous (unregistered) in reply to Your Name
    Your Name:
    Is anyone familiar enough with CMMI to know whether all of this logging is "mandatory"? I worked for an organization that was working towards their certification, but that was 10+ years ago and I purged all that from my brain.
    CMMI says virtually nothing about coding practices. It's entirely about organisation: Software development processes, repeatability, documentation, quality assurance and the like.
  • noone (unregistered)

    You often see this pattern in embedded systems....

  • Ale (unregistered)

    ioccc,

    You might have done that as a joke, but to actually improve it a lot (from the error handling point of view, of course), change Exception ex to RuntimeException ex, and rethrow that after logging, instead of returning false. Or just get rid of the generic catch all together, and let unexpected exceptions go up to a level that can handle them right. (and decide if you should warn the user and/or close with a fatal message, or whatever).

    Of course, the method would still be useless, would have ridiculous logging and all... But at least it would be handling its exceptions right.

  • Ale (unregistered)

    Of course, you should always avoid nullpointers instead of catching them. Java compilers even have warnings for unchecked potencial null references. But anyway, catching it would be better than the original.

  • (cs)

    You guys are missing TRWTF. The CTO said the people responsible for this abomination will make his team look bad. Imagine what quality of WTFs we'll get from their team.

  • (cs) in reply to Anonymous
    Anonymous:
    Your Name:
    Is anyone familiar enough with CMMI to know whether all of this logging is "mandatory"? I worked for an organization that was working towards their certification, but that was 10+ years ago and I purged all that from my brain.
    CMMI says virtually nothing about coding practices. It's entirely about organisation: Software development processes, repeatability, documentation, quality assurance and the like.

    Sounds similar to ISO 9000 and all of its spawn. It's easy to standardize measurements, documentation, etc. Unfortunately, it's not easy to standardize design, innovation, or creativity.

  • Anon (unregistered) in reply to akatherder
    akatherder:
    Andreas:
    We had the same experience with our CMMI Level 5 offshore-team. These guys had great processes that forced them to write
    if (a == b){
      return "something";
    }
    return "soemthingElse";
    
    instead of
    if (a == b){
      return "something";
    } else {
      return "soemthingElse";
    }
    

    The default config of some IDE (maybe Visual Studio) gives you warnings for the second code-block because it thinks you don't have a guaranteed return condition.

    Not Visual Studio. At least not any version of it I've ever used.

  • (cs) in reply to mypalmike
    mypalmike:
    I like the fact that this can return false:
    public static boolean equalToSelf(float n) {
       return n == n;
    }
    

    I'm pretty sure it cannot... floats don't "miraculously" change value, the bits are still the same. What happens to floats are that sometimes the arithmetic is "fuzzy" and the result of a function may not be exactly what you would expect. The value of a float in memory will always be the same (unless the memory is faulty).

  • (cs) in reply to ToAshamedToName
    ToAshamedToName:
    Ok so logging each call to isValidNumber() is a wtf, but isn't having a paramater of type Integer also a wtf? Won't the call to the method fail if anything but an integer is passed?

    It wouldn't even compile pre Java 5, but from 5 forwards, we get auto-boxing of primitive types (similar, but not quite like, auto-boxing in C#).

    So if you were to pass an int variable, say x, as an argument to a function taking an Integer, the compiler would create an Integer object initialized with x. Same when assigning an Integer to a int (or any standard primitive wrapper to/from an actual primitive type.)

    It's sort of a helpful feature, but it can cause a NPE (and many programmers are awfully unaware of that.) I don't quite like auto-boxing as in Java because, quite frankly, there is a lot of pre-5 code out there, and most Java programmers are "stream-of-consciousness" programmers. That is, they just spit code without considering things like this:

    
    int i = integerObjectComingFromSomewhere; // NPE waiting to happen when careless.
    
    

    Autoboxing would work wonderfully if java had some sort of "elvis" operator, but it doesn't so.... one has to be conscious about the possibility of nulls when relying on autoboxing.

    Other than having an Integer argument (which is not necessarily a bad thing), the method is a wtf simply because of its excessive usage of logging statements. Worse still, the log statements are of the "Captain Obvious" type, completely useless.

    When you see code like that, it is usually a sign of lack of experience programming and/or using a debugger.

    Another thing, kinda debatable, is the reliance of an exception for determining if a string is numeric or not. Exceptions are expensive.

    But there aren't any clean alternatives in Java. We could use scanners, parsers or Character.isDigit in a loop, but these are awfully clunky and easy to get wrong. Having an optimized, built-in "isNumeric" method somewhere (anywhere) in Java that does not rely on exceptions, that is something I just don't know why it doesn't exist in Java. Oh well.

  • Forumtroll (unregistered) in reply to ath
    ath:
    I wonder if you could write a "log-file-compiler" taking the log file as input and producing a fully functional program?

    Thank you, Ath! I've decided that this will be my next opensource project.

    I'll try to use as much of the content I find here, and I'll keep Alex and the gang updated whenever they require it.

    Please disregard my nickname this time.

  • (cs) in reply to Ale
    Ale:
    ioccc,

    You might have done that as a joke, but to actually improve it a lot (from the error handling point of view, of course), change Exception ex to RuntimeException ex, and rethrow that after logging, instead of returning false. Or just get rid of the generic catch all together, and let unexpected exceptions go up to a level that can handle them right. (and decide if you should warn the user and/or close with a fatal message, or whatever).

    Of course, the method would still be useless, would have ridiculous logging and all... But at least it would be handling its exceptions right.

    That depends on context. If some situations, you do want to throw an exception (and let/pray an upper-level exception handler catch it).

    In other cases, what is required is to return a boolean value instead.

    Again, it's all dependent on the context, on what the code is supposed to do.

  • Lothar (unregistered) in reply to chewbacha
    chewbacha:
    mypalmike:
    I like the fact that this can return false:
    public static boolean equalToSelf(float n) {
       return n == n;
    }
    

    I'm pretty sure it cannot...

    Famous last words ;-)

    chewbacha:
    floats don't "miraculously" change value, the bits are still the same. What happens to floats are that sometimes the arithmetic is "fuzzy" and the result of a function may not be exactly what you would expect. The value of a float in memory will always be the same (unless the memory is faulty).

    And then there are values that are by definition equal to nothing, even to themselves:

      float f1 = Float.NaN;
      float f2 = Float.NaN;
    
     System.out.println(f1 == f2);
    

    outputs false.

  • Jeff K. (unregistered)

    You know, some other WTF programmer is going to see this method and try to use it as it might have originally been intended - to check the validity of the value entered into a text box. But since the method only takes an Integer parameter, he/she is going to parse the text into an Integer to get around the compiler error.

    Hmm...

  • Ale (unregistered) in reply to luis.espinal
    luis.espinal:
    Ale:
    ioccc,

    You might have done that as a joke, but to actually improve it a lot (from the error handling point of view, of course), change Exception ex to RuntimeException ex, and rethrow that after logging, instead of returning false. Or just get rid of the generic catch all together, and let unexpected exceptions go up to a level that can handle them right. (and decide if you should warn the user and/or close with a fatal message, or whatever).

    Of course, the method would still be useless, would have ridiculous logging and all... But at least it would be handling its exceptions right.

    That depends on context. If some situations, you do want to throw an exception (and let/pray an upper-level exception handler catch it).

    In other cases, what is required is to return a boolean value instead.

    Again, it's all dependent on the context, on what the code is supposed to do.

    Hum, no, sorry.

    For an unexpected error, you should't return false. It's a very bad pattern. Common, but very bad nevertheless.

    Returning false, null, -1 or any other stupid values when unexpected errors happen, removes from the caller the opportunity to properly handle the error.

    Let's think of the indexOf function in specific collection, for example. When it can't find a value (an expected and banal error), it returns -1. If anything else happens, it should throw an exception. That's the correct behavior. I can check for -1, and I'll know that it doesn't have what I'm looking for.

    If it just decides to return -1 on weird errors, when it returns -1, all I know is that it couldn't find it, but can't be sure about the reason. Most of the time it doesn't have the item we're searching, but maybe the collection detected some internal inconsistence, had a nullpointer, or whatever. That's a programming mistake, and as such, has to go up as a runtime exception.

  • Vlad Patryshev (unregistered) in reply to steenbergh

    when the parameter is null.

  • (cs) in reply to highphilosopher
    highphilosopher:
    IF an integer is parsed in the woods, and no one is around to hear it fail, does it raise an exception?

    Excellent

  • High Management (unregistered) in reply to frits
    frits:
    Sounds similar to ISO 9000 and all of its spawn. It's easy to standardize measurements, documentation, etc. Unfortunately, it's not easy to standardize design, innovation, or creativity.
    ... which is why we have to wipe it out! How can we manage something we don't understand and can never produce?
  • aristos_achaion (unregistered) in reply to Someone You Know
    Someone You Know:
    sarge:
    Anyone else noticed the mysterious methodName variable at the top? Has to be a static member is it's a static method. Hope this isn't multi-threaded code.

    People who are new to programming often don't entirely grok the concept of using a literal value directly in an expression of some kind; you'll see them constantly creating useless variables because they don't understand that literal values can be used outside of assignment operations. Such people also have trouble with using the return value of an expression or method call directly in an expression, without assigning it to a variable first.

    This is particularly common with students learning Java with no prior programming experience, which is not a slight against the language itself, but more against the way it is taught in American universities.

    If it were just wanting to assign something to a variable before use, it'd be relatively harmless (actually, I find that practice to be useful sometimes as a sanity check). The problem is, it's being assigned to a global, and, because it's a static method, that's got to be a static global.

    Now, let's assume this method is in a class called TestMethods. Since you can't have a static class (annoying), you can create instances of TestMethods, even in different threads. Now, let's assume that there's another function that takes a while. Say,

    public static void TakeALongTimeAndLog(){ methodname = "TakeALongTimeAndLog"; Thread.sleep(3600); logger.fine(methodName + " slept 3600 seconds"); }

    Say you invoke TakeALongTimeAndLog in one string, and then isValidNumber in another. Guess what TakeALongTimeAndLog thinks the method name is?

  • KLOCker (unregistered) in reply to chewbacha
    chewbacha:
    mypalmike:
    I like the fact that this can return false:
    public static boolean equalToSelf(float n) {
       return n == n;
    }
    
    I'm pretty sure it cannot... floats don't "miraculously" change value, the bits are still the same.
    Hmmm... I wanted to test this assertion by looping through all possible values of a float and counting up the trues and falses. I know how to loop integers, but not floats. Could someone plezz send me teh codez?
  • DaveE (unregistered)

    Having been through a CMMI evaluation in a Level-4 rated origanization, I have to say: CMM(I) is not about the code, it's about the process. Level 5 organisations are not necessarily good at coding, they're good & theoretically self-improving process junkies.

  • aristos_achaion (unregistered) in reply to Ale
    Ale:
    luis.espinal:
    Ale:
    ioccc,

    You might have done that as a joke, but to actually improve it a lot (from the error handling point of view, of course), change Exception ex to RuntimeException ex, and rethrow that after logging, instead of returning false. Or just get rid of the generic catch all together, and let unexpected exceptions go up to a level that can handle them right. (and decide if you should warn the user and/or close with a fatal message, or whatever).

    Of course, the method would still be useless, would have ridiculous logging and all... But at least it would be handling its exceptions right.

    That depends on context. If some situations, you do want to throw an exception (and let/pray an upper-level exception handler catch it).

    In other cases, what is required is to return a boolean value instead.

    Again, it's all dependent on the context, on what the code is supposed to do.

    Hum, no, sorry.

    For an unexpected error, you should't return false. It's a very bad pattern. Common, but very bad nevertheless.

    Returning false, null, -1 or any other stupid values when unexpected errors happen, removes from the caller the opportunity to properly handle the error.

    Let's think of the indexOf function in specific collection, for example. When it can't find a value (an expected and banal error), it returns -1. If anything else happens, it should throw an exception. That's the correct behavior. I can check for -1, and I'll know that it doesn't have what I'm looking for.

    If it just decides to return -1 on weird errors, when it returns -1, all I know is that it couldn't find it, but can't be sure about the reason. Most of the time it doesn't have the item we're searching, but maybe the collection detected some internal inconsistence, had a nullpointer, or whatever. That's a programming mistake, and as such, has to go up as a runtime exception.

    But, in this case, the (very bad) programmer thinks that his exception-handler will only catch (expected) number-format exceptions, and thus returning false when the provided Integer isn't an integer. The problem is that if you can cram the data in question into an Integer, you've already tested every case except '== null'. There shouldn't be an exception rethrown, because this isn't a case of a valid exception being handled, it's an attempt to exploit exceptions to test an expected condition.

  • (cs) in reply to Fred
    Fred:
    public static boolean isUniverseStillDeterministic(Integer number) {
            try {
                Integer.parseInt(number.toString());
            } catch(Exception ex) {
                return false; 
            }
            return true;      
        }
    
    You're going to want to call this about 100 times a second, because if the Universe ever stops being deterministic you'll want to know right away that your calculations and logic are no longer reliable.

    Where it really gets interesting, then, is the code that calls isUniverseStillDeterministic. What are you going to do when you get a false? Better yet, how do you test that branch in your code? And if it does happen, you better log as much detail as possible to help unravel some of the fundamental problems of quantum mechanics.

    This code is incorrect. It can return true - a result with which any person knowing quantum mechanics (or QED) would disagree.

  • aristos_achaion (unregistered) in reply to luis.espinal
    luis.espinal:
    But there aren't any clean alternatives in Java.

    Couldn't you just use regex matching to match a string to "\d+.?\d*" or similar? Or, for integers only (as here), just "\d+"?

  • Ale (unregistered) in reply to aristos_achaion
    aristos_achaion:
    Ale:
    luis.espinal:
    Ale:
    ioccc,

    You might have done that as a joke, but to actually improve it a lot (from the error handling point of view, of course), change Exception ex to RuntimeException ex, and rethrow that after logging, instead of returning false. Or just get rid of the generic catch all together, and let unexpected exceptions go up to a level that can handle them right. (and decide if you should warn the user and/or close with a fatal message, or whatever).

    Of course, the method would still be useless, would have ridiculous logging and all... But at least it would be handling its exceptions right.

    That depends on context. If some situations, you do want to throw an exception (and let/pray an upper-level exception handler catch it).

    In other cases, what is required is to return a boolean value instead.

    Again, it's all dependent on the context, on what the code is supposed to do.

    Hum, no, sorry.

    For an unexpected error, you should't return false. It's a very bad pattern. Common, but very bad nevertheless.

    Returning false, null, -1 or any other stupid values when unexpected errors happen, removes from the caller the opportunity to properly handle the error.

    Let's think of the indexOf function in specific collection, for example. When it can't find a value (an expected and banal error), it returns -1. If anything else happens, it should throw an exception. That's the correct behavior. I can check for -1, and I'll know that it doesn't have what I'm looking for.

    If it just decides to return -1 on weird errors, when it returns -1, all I know is that it couldn't find it, but can't be sure about the reason. Most of the time it doesn't have the item we're searching, but maybe the collection detected some internal inconsistence, had a nullpointer, or whatever. That's a programming mistake, and as such, has to go up as a runtime exception.

    But, in this case, the (very bad) programmer thinks that his exception-handler will only catch (expected) number-format exceptions, and thus returning false when the provided Integer isn't an integer. The problem is that if you can cram the data in question into an Integer, you've already tested every case except '== null'. There shouldn't be an exception rethrown, because this isn't a case of a valid exception being handled, it's an attempt to exploit exceptions to test an expected condition.

    Adding the catch for the format exception and returning false is abusing exceptions, but isn't a error handling mistake.

    That would be right, if he added the correct catch case. Since he didn't, it can catch anything. Even a bug on Integer class or something. Thus, runtime exceptions should ever be rethrown, even if they are very unlikely to happen. It's not any difficult, just catch only what you need, and let the rest go up. If you want to, catch it, log it, and let it go.

    Don't ever assume "no other exceptions can happen". Even when true, it's a horrible pattern, and will lead to future very hard to detect problems once the code is changed.

  • Anonymous Coward (unregistered) in reply to Anonymous
    Anonymous:
    Your Name:
    Is anyone familiar enough with CMMI to know whether all of this logging is "mandatory"? I worked for an organization that was working towards their certification, but that was 10+ years ago and I purged all that from my brain.
    CMMI says virtually nothing about coding practices. It's entirely about organisation: Software development processes, repeatability, documentation, quality assurance and the like.
    Feature this comment. Surprised the discussion went so long without someone mentioning this.
  • Rodney (unregistered) in reply to Andreas
    Andreas:
    We had the same experience with our CMMI Level 5 offshore-team. These guys had great processes that forced them to write
    if (a == b){
      return "something";
    }
    return "soemthingElse";
    

    What am I missing here? What's wrong with that approach? Or is it just that their procedures forced that style over the equivalent if/else?

    Captcha: No-one gives a crap what your captcha was.

  • http://consultuning.blogspot.com (unregistered)

    As a previous poster said, CMMI does not say a word about coding or logging practices. It's all about the process followed to create software.

    This process will be documented and measurable and thus will be manageable and repeatable (I stil have issues with the fixation on having to measure something to be able to manage it, but...) So yes, a CMMI level 5 organization can assure you that they have the right processes in place to always deliver the same level of quality. Even if it is absolutely awful.

  • Lawrence (unregistered) in reply to Rodney
    Rodney:
    Captcha: No-one gives a crap what your captcha was.
    Wow! I've never had that one, myself. Please post any other unusual captchas you see, because I'm trying to build a complete collection for my SPAMbot.
  • SanderD (unregistered)

    hmm. lets use this code in a server app or something? with a lot of request per second :) and see what happens? :D

  • (cs) in reply to Lothar
    Lothar:
    chewbacha:
    mypalmike:
    I like the fact that this can return false:
    public static boolean equalToSelf(float n) {
       return n == n;
    }
    

    I'm pretty sure it cannot...

    Famous last words ;-)

    chewbacha:
    floats don't "miraculously" change value, the bits are still the same. What happens to floats are that sometimes the arithmetic is "fuzzy" and the result of a function may not be exactly what you would expect. The value of a float in memory will always be the same (unless the memory is faulty).

    And then there are values that are by definition equal to nothing, even to themselves:

      float f1 = Float.NaN;
      float f2 = Float.NaN;
    
     System.out.println(f1 == f2);
    

    outputs false.

    touche

    although, I'd use this as an example instead:

            static void Main(string[] args)
            {
                float f1 = float.NaN;
                Console.WriteLine((f1 == f1).ToString());
                Console.ReadLine();
            }
    

    As that's how I verified it, more closely resembles the actual test (comparing the same variables).

    "Miraculously" this does work:

                float f1 = float.NaN;
                Console.WriteLine(f1.ToString() == f1.ToString());
                Console.ReadLine();
    

    (and yes, I use c# not java, but the results should be the same.)

  • Rhys (unregistered)

    I kept thinking 'I've seen worse' as I was reading, thinking thats ok, it'll catch strings and things, till I saw (Integer number). haha

  • Lothar (unregistered) in reply to chewbacha
    chewbacha:
    although, I'd use this as an example instead:
            static void Main(string[] args)
            {
                float f1 = float.NaN;
                Console.WriteLine((f1 == f1).ToString());
                Console.ReadLine();
            }
    

    As that's how I verified it, more closely resembles the actual test (comparing the same variables).

    "Miraculously" this does work:

                float f1 = float.NaN;
                Console.WriteLine(f1.ToString() == f1.ToString());
                Console.ReadLine();
    

    (and yes, I use c# not java, but the results should be the same.)

    Nope. See e.g. http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Float.html#equals(java.lang.Object):

    The linked Javadoc:
    Note that in most cases, for two instances of class Float, f1 and f2, the value of f1.equals(f2) is true if and only if
       f1.floatValue() == f2.floatValue()
    

    also has the value true. However, there are two exceptions:

    * If f1 and f2 both represent Float.NaN, then the equals method returns true, even though Float.NaN==Float.NaN has the value false.
    * If f1 represents +0.0f while f2 represents -0.0f, or vice versa, the equal test has the value false, even though 0.0f==-0.0f has the value true. 
    

    This definition allows hash tables to operate properly.

  • Real Pedantic Bastard (unregistered) in reply to highphilosopher
    highphilosopher:
    IF an integer is parsed in the woods, and no one is around to hear it fail, does it raise an exception?

    No, but you can always deduce that it did from the logs on the ground.

Leave a comment on “isValidNumber()”

Log In or post as a guest

Replying to comment #:

« Return to Article