• Tama (unregistered) in reply to aliquam
    aliquam:
    the .equals() is to slow to be used in a large series of if statements...

    You should only use it when you know the majority of the test will be true.

    If you know the majority of the test will be false use the == operator which is slower when true, but twice as fast when false...

    Yes, because obviously this is the 10% of the code where the application spends 90% of its time... Long live premature optimization!

    First of all, your "optimization" is semantically incorrect:

    String s1 = "foo";
    String s2 = new String(s1);
    System.out.println(s2 == s1); // Prints false
    System.out.println(s2.equals(s1)); // Prints true

    Second of all, your claim about the speed of "==" is unsubstantiated; I have run the test above with various values for s2 in a loop of 10 millions iterations and measured the timings in each case:

    • when s2 = s1, "==" yields 28ms while "equals" yields 83ms
    • when s2 = "bar", "==" yields 28ms while "equals" yields 163ms

    Third of all, this block of code is most certainly not worth optimizing anyway: unless there are thousands or millions of such tests performed sequentially within this method, the time spent in this particular piece of code per se is ridiculously small. And thinking about cases where the whole method itself would be invoked thousands of times sequentially is irrelevant, since the execution time of the whole method is largely dominated by the time during which it waits for the user input.

    In any case:

    • you don't sacrifice correctness for speed
    • when you do performance optimization:
      • start by doing something simple and correct
      • measure to find out the bottlenecks (you can take a wild guess, but you may be wrong and spend time trying to optimize something that won't help solve your performance issue)
      • try some optimization
      • measure again; you may find that the bottleneck is NOT where you assumed it would be, either because your optimization is irrelevant to the source of the bottleneck, or because your optimization was not as good as you thought.

    Now, to come back to the original article, maybe the author took inspiration from the infamous over-simplistic example of the XP practice of writing the simplest code that passes test cases (the stupid example in which to write a function add(x, y), you start by returning 2 because your test case only exercises (1,1); and then you fix it when you add more test cases), and along the way forgot the word "simplest"... was impregnated with XP practices such as "write the simplest code that passes the test cases

  • (cs)

    It doesn't accept "indoubetedly"? Tsk.

  • darlinton (unregistered)

    if ( "maybe".equals(answer) ) { return ( rand() > 0.5 ); }

  • Chris (unregistered) in reply to Jerim
    Jerim:
    Jota, I see that scenario all the time. Every time some programmer rails against the stupidity of the previous programmer, I just start playing scenarios like that in mind. I can't tell you how many decent programmers out there have bad reputations simply because the users demanded that they program it that way. That is why it is vital to only attach your name to good code and leave no trace of your identity on bad code.
    I like to document bad code with references to the specification that required it. I'm sure there are some lines of code commented with stuff like, "Wow, our users are complete idiots and I had to do this to appease them." somewhere in our code base.

    I can also remember writing comments like, "PHB thinks this need to be done this way, but I disagree. It is wrong for reason ______".

  • aliquam (unregistered) in reply to Tama
    Tama:
    ...
    Yea what he did was so much better than the following:
    return answer.equals("y")
    	|| answer.equals("yes")
    	|| answer.equals("yep")
    	|| answer.equals("ok")
    	|| answer.equals("proceed")
    	|| answer.equals("affirmative")
    	|| answer.equals("positive")
    	|| answer.equals("correct")
    	|| answer.equals("aye")
    	|| answer.equals("fine")
    	|| answer.equals("yar");

    even when XP is involved :eyeroll:

  • Lally (unregistered)

    Why didn't the dev just use a table of strings? I mean really, look at it.

  • EnterpriseArchitecture (unregistered)

    The real wtf is where are the software patterns here?

    We can introduce the ChoiceAbstractFactory class and interface. We can follow this up with derived YesFactory, NoFactory, and FileNotFoundFactory classes and interfaces. Of course the factory should create instances from an XML config file, something like

    <choices> <choice> <choiceid>somebigguid</choiceid> <choiceValue>yup</choiceValue> </choice> <choice> <choiceid>someotherbigguid</choiceid> <choiceValue>si</choiceValue> </choice> <choices>

    Of course lets not forget everything should be in a resource file, so we can handle international choices via satellite assemblies. I'm sure we can fit in more XML everywhere.

  • more randomer than you (unregistered) in reply to grg
    tdittmar:
    andrewbadera:
    Soooooo .... why did it hang? Looks like valid script to me.
    Hm. Enter "Y" and see what happens... Is my sarcasm detector broken?
    grg:
    THE REAL WTF IS THEY DID NOT HANDLE THE CASE WHERE THEY WERE AN IDIOT AND HAD THEIR SHIFT-LOCK ON.

    THEN YOU'D NEED ALSO THE UPPER CASE COMPARISONS TOO !!

    This is a small part of the code. Presumably the string has already been cast to lower case.

    James:
    This would save you all those annoying "if" statements. Not that that's even TRWTF.
    if(Array.IndexOf(
      new string[]{ "yes","y","ok","why not", [...], "yar" },
      userInput.ToLower())
      > -1)
    {
        // do the yes stuff
    }
    else
    {
        // do the no stuff
    }
    

    Although you might not want to create a new array every time you call this method. It looks like it is intended to be used throughout the application.

    Kermos:
    Ok the first WTF is, if it's a yes/no prompt why not have two buttons? A combo box containing yes/no a choices? Why a text field?

    The things that users can do with text fields are just horrendous. Don't ever give users text fields unless you have to! I have to deal with a bunch of crap stored into text fields that should have been combo box choices. Did you know there are apparently 38 ways to specify "Ground" as a shipping method? Try to run a query with garbage like that in a database to see all shipments that left or arrived via ground shipping.

    Not all applications have GUI's.

    Saint Gerbil:
    Why type "yes" when you can just hit "y" I've just tripled my productivity.
    'y' + Enter = 2 keystrokes 'yes' + Enter = 4 keystrokes

    Still, your boss will be pleased, and you can leave the office at 1pm each day.

    KenW:

    Two problems.

    First, the very first thing listed isn't "Y". It's "y". They're not the same.

    Second, after looking at the code, you "assumed" there was a cast of 'answer' to lowercase as the first thing it does. Given the quality of the code submitted, this is a ridiculous assumption.

    Ridiculous is assuming that the code didn't make such an obvious cast to lower case considering that there were no reports of it having problems with this in the story. The code is silly, however there is nothing mentioned to lead us to believe that it is wrong.

    KenW:
    The programmer's first mistake. He should have not added anything, but simply checked the first letter for "Y" or "y" and ignored the request.
    bjolling:

    No, TRWTF is that the original developer had used the "ReadLine" function instead of using "ReadKey" and continue the processing as soon as someone hit the 'y' key

    Because every single word beginning with the letter 'y' means 'yes'? This code might be called by critical areas of the system and doing such a naieve test for confirmation might not be wanted.

    aliquam:
    the .equals() is to slow to be used in a large series of if statements...

    You should only use it when you know the majority of the test will be true.

    If you know the majority of the test will be false use the == operator which is slower when true, but twice as fast when false...

    Oh my. When measuring the length of time it takes for different parts of a program to run, user input is pretty much as slow as it gets. You could test for .equals() thousands of times without having any noticeable effect on the time it takes to run the application.

    ..Then there is the fact that == and .equals() are very different things. == tests for equal memory addresses, .equals() tests for whatever the object tells it to test.

  • Yorinaga (unregistered)

    The real WTF is not that they used all these options for yes and no, provided that that was required in the specification.

    The real WTF is not using a hashtable with the user response as the key and the return value as the value.

    O(1)

  • BillyBob (unregistered) in reply to grg
    grg:
    THE REAL WTF IS THEY DID NOT HANDLE THE CASE WHERE THEY WERE AN IDIOT AND HAD THEIR SHIFT-LOCK ON.

    THEN YOU'D NEED ALSO THE UPPER CASE COMPARISONS TOO !!

    How do you know he didn't lower case the string stored in answer before the comparision?

  • I suppose so (unregistered) in reply to ParkinT

    You missed "narp".

  • (cs) in reply to amischiefr
    amischiefr:
    mauve:
    brillohead:
    yes, because checking if the memory location of the input is the same as the memory location of my static strings is going to give me exactly the result im looking for...

    True, if you intern the input string: http://java.sun.com/javase/6/docs/api/java/lang/String.html#intern()

    Yet another reason the guys at Sun should stop fucking with the API. Why replace .equals() with something that is exactly the same?

    String.intern() is not a replacement for .equals(). It's used by the compiler to make sure that hard-coded strings that are equal are represented by the same String object at runtime, so an expression like ("A" == "A") will be true.

  • asdf (unregistered)

    So what made it hang?

  • Max Battcher (unregistered)

    From now on I figure all text-prompts most respond affirmatively to the piratical "Yar", otherwise the programmers shall be confirmed racist against proud Buccaneer-Americans.

  • James (unregistered) in reply to ParkinT

    You forgot "negatory"

  • uhhh.... (unregistered) in reply to cconroy

    What's Pirate for "no"? "Yar with a more negative inflection"

  • Masklinn (unregistered) in reply to James
    James:
    This would save you all those annoying "if" statements. Not that that's even TRWTF.
    if(Array.IndexOf(
      new string[]{ "yes","y","ok","why not", [...], "yar" },
      userInput.ToLower())
      > -1)
    {
        // do the yes stuff
    }
    else
    {
        // do the no stuff
    }
    

    I say, you really want a (private final static unmodifiable) Set here, HashSet's lookup is in O(1) while Array#indexOf should be in O(n). Also, Set#contains would return a boolean (simpler code) and marks your intent much more clearly than Array#indexOf does.

  • peterb (unregistered)

    Apart from the fact that it's not very elegant code, I don't see where time is an issue. Okay, getting 26 words might take a few moments, but even with cut and paste it's not even a minute to enter them. And it's even faster with a macro.

  • Vipsy (unregistered) in reply to ParkinT

    Nah Nope Nada Uh ah no way negative absolutely not Fer sure Non Don't think so Maybe Ofcourse I will If time permits 110%

  • Anonymoose (unregistered) in reply to Mee
    Mee:
    If you ask a pirate something and they don't want to answer something meaning "yes", you get stabbed.

    What if you ask him "Are you going to stab me?"

  • fiber (unregistered)

    couldn't he at least use else ifs?!?!

  • Roy Sigurd Karlsbakk (unregistered) in reply to BlueKnot

    Try this language http://www.tlc-systems.com/babbage.htm

    "Structured languages banned GOTOs and multi-way conditional branches by replacing them with the simpler IF-THEN-ELSE structure. Babbage has a number of new conditional statements that act like termites in the structure of your program: WHAT IF - Used in simulation languages. Branches before evaluating test conditions.

    OR ELSE - Conditional threat, as in: "Add these two numbers OR ELSE!"" ...

  • (cs)

    Um, supprised no ones mentioned that equalsIgnoreCase(String str) might work a little more often :P

    Confirm?>YES
    --command not recognised--
    Confirm?>Y
    --command not recognised--
    Confirm?>YEP
    --command not recognised--
    Confirm?>Yes please
    --command not recognised--
    Confirm?>*sigh*
    --command not recognised--
    
  • Florian (unregistered)

    If you wonder why it hung after the prompt - I think the user made a typo and the whole code looks like this:

    protected boolean checkAnswer(String answer) {
    	
    	boolean answered = false;
    	while (!answered) {
    		if (answer.equals("y")|| answer.equals("yes") || answer.equals("yep")) {
    		    return true;
    		}
    		if (answer.equals("ok")) {
    		    return true;
    		}
    		if (answer.equals("proceed")) {
    		    return true;
    		}
    		if (answer.equals("affirmative")) {
    		    return true;
    		}
    		if (answer.equals("positive")) {
    		    return true;
    		}
    		if (answer.equals("correct")) {
    		    return true;
    		}
    		if (answer.equals("aye")) {
    		    return true;
    		}
    		if (answer.equals("fine")) {
    		    return true;
    		}
    		if (answer.equals("yar")) {
    		    return true;
    		}
    		
    		//and so on ...
    		
    		if (answer.equals("n")) {
    			return false;
    		}
    		if (answer.equals("no")) {
    			return false;
    		}
    		if (answer.equals("nope")) {
    			return false;
    		}
    		if (answer.equals("cancel")) {
    			return false;
    		}
    		if (answer.equals("negative")) {
    			return false;
    		}
    	}
    }
  • Winslow Theramin (unregistered)
    1. This story - like all the stories on this site - is just made up out of whole cloth. Never happened. But, what the heck, I'll occasionally dip in here to see what kind of BS people are willing to believe.

    2. Is the funny part of the story the fact that it can't deal with "answer" being equal to null?

    The code should be, e.g.:

    if("yar".equals(answer)) { }

    etc., ...

  • Gandolf989 (unregistered)

    I just couldn't help myself. I had to rewrite it. He forgot the foreign versions of true and false. oiu, ja, si, the list could go on forever. no???? (meaning yes)

    while (! ( String.Compare(answer, "y", true) || String.Compare(answer, "yes", true) || String.Compare(answer, "n", true) || String.Compare(answer, "no, true) ( { System.out.println("dude it's either yes or no!!!");
    System.out.println("Try again!!!"); -- insert code for getting input
    }

    if ( String.Compare(answer, "y", true) || String.Compare(answer, "yes", true) { return true; } else return false; }

  • (cs) in reply to Winslow Theramin
    Winslow Theramin:
    1. This story - like all the stories on this site - is just made up out of whole cloth. Never happened. But, what the heck, I'll occasionally dip in here to see what kind of BS people are willing to believe.

    Rumors of your intelligence, like all the rumors you ever hear, are just made up out of whole cloth. Not a fact. But what the heck, we'll occasionally allow you to visit and post nonsense just to see what kind of idiotic things you'll say.

    Winslow Theramin:
    2. Is the funny part of the story the fact that it can't deal with "answer" being equal to null?

    Nah. Nope. No. Never. Nil. Nyet. Nanu nanu.

    The funny part of the story is that you obviously have no real experience with bad code (other than that you yourself have written, of course). Anyone with real experience has seen stupid source code like this (and worse), because they've dealt with the type of programmer that would do this - you know, people like yourself. (I include you because you obviously haven't seen bad code like this before, which means you don't know how to recognize it when you see it, which means it's probably your code. HEY! I just figured out where the code from the OP came from! YOU WROTE IT!!!!)

  • g (unregistered) in reply to Mee

    its Nay moron

  • anon (unregistered) in reply to BlueKnot
    BlueKnot:
    What, no provision for "maybe"?

    You mean FILE_NOT_FOUND?

  • Joe (unregistered) in reply to Jota
    Jota:
    Perhaps this was just a frustrated developer who was tired of dealing with bug reports.

    QA: When I typed "yes" it didn't work. Please fix.

    Developer: OK, "yes" should work the same as "y" now, and "no" should be the same as "n".

    QA: When I typed "ok" it didn't work. That is standard for dialog boxes. The prompt should be more forgiving. Please fix.

    Developer: But this isn't a dialog box... oh, whatever. There, now "ok" and "cancel" should be accepted as well.

    QA: The text on the page before mentions the word "proceed", so the prompt should accept that as well. Please make the prompt more forgiving.

    Developer: Fine. I'll make the prompt more forgiving. You want to type "proceed"? Here, you can type "proceed"! How about "affirmative"? You want "affirmative"? Or maybe "positive"? What about pirates? Aye? Do we have any pirates using our software? Gotta think of the pirates, yep! Hey, "yep" -- you want "yep" too? Have a "yep"! Have whatever you want! Is that forgiving enough? IS THAT FORGIVING ENOUGH?

    QA: When I just hit enter, nothing happens. Hitting enter should default to "yes".

    Developer: <hangs self, and Craig M is hired to replace him>

    Perhaps instead of suicide, Requirements would be in order? That way, the mean QAer wouldn't have to propose so many solutions.

    ... I'm just sayin'

  • JD (unregistered) in reply to BlueKnot

    now you are talking risk processing

  • Flo (unregistered) in reply to BlueKnot
    BlueKnot:
    What, no provision for "maybe"?

    return FileNotFound;

  • IByte (unregistered) in reply to Adam
    Adam:
    That looks like it'll be a bitch to internationalize
    Are they going to include phonetic transcriptions too? The Greek word for 'yes' sounds like 'ne', which also happens to mean 'no' in Czech...
  • Sellnosoup (unregistered) in reply to TakeASeatOverThere
    TakeASeatOverThere:
    if (answer.equals("yar")) { return true;
    Obviously the application was designed for pirates.

    Does that mean its pirate software?

  • BentFranklin (unregistered)

    "Code rage" made me laugh.

    Did you just make that up or is it already a meme?

  • BentFranklin (unregistered)

    Never mind. I should have Googled it first. Is should Google everything first. But then I would never have time to ask any questions.

  • Atlanta (unregistered)

    IMHO this looks like a pragmatic approach to code around user input to me... This shows an ability to be creative and consider an end user. I'd hire this individual, in lieu of the non-creative 'One way to skin a cat' coder.

  • .Net rulz the universe - all else blows (unregistered)

    Why not use a real programming language which has a simple messagebox class which returns constants... Hell, you could even localize it then as well, imagine that.

    Some people should never be allowed near a compiler, then end up draining the world economy :P

  • anonymous coward (unregistered)

    What about the Cowboy Neal option?

  • plaga (unregistered) in reply to Gandolf989
    Gandolf989:
    I just couldn't help myself. I had to rewrite it. ...

    Your code is crazy too, so I fixed it:

    while (! ( String.Compare(answer, "y",   true) || 
               String.Compare(answer, "yes", true) ||
               String.Compare(answer, "n",   true) ||
               String.Compare(answer, "no,   true) ( {
       System.out.println("dude it's either yes or no!!!");  
       System.out.println("Try again!!!");
    -- insert code for getting input  
    }
    
       return ( String.Compare(answer, "y",   true) || 
         String.Compare(answer, "yes", true);
    }
  • ChiefCrazyTalk (unregistered) in reply to I'm Cornfused
    I'm Cornfused:
    I'm also not seeing why it would hang... (unless a 1 ms delay constitutes a 'hang')

    The if structure isn't nested, and doesn't call some horribly recursive function... so unless it's running on a TI-83 or something, the 26 if statements really shouldn't take any time at all to run through.

    I'm also not sure which language this is, and whether or not .equals() will actually compare the values of the strings. If it's checking for the objects to actually be the same instance or something weird like that, then yeah, there's going to be issues.

    Any explanations, anybody?

    Yes. The bug was elsewhere.

  • ChiefCrazyTalk (unregistered) in reply to anonymous coward
    anonymous coward:
    What about the Cowboy Neal option?
    Mod slashdotter down as troll!
  • (cs)

    I was almost impressed except for the lack of 'yarp' and 'narp'.

  • consequat (unregistered)

    The Real Wtf is that such answers must be placed in arrays like (sorry for my python, i'm lazy to rewrite it to java):

    answers_yes=['yap', 'yes'] answers_no=['no','nope'] if answer in answers_yes: return True if answer in answers_no: return False return FileNotFound

  • RHenningsgard (unregistered)

    I wrote something similar once, although it was more multi-lingual ("da", "si", "oiu" and so on) than slangish. My favorites, though, were "perhaps" and "maybe". I implemented these for Monte-Carlo testing, where "perhaps" returned true 25% of the time, and "maybe" returned true 50% of the time.

  • (cs) in reply to cconroy
    cconroy:
    TakeASeatOverThere:
    if (answer.equals("yar")) { return true;
    Obviously the application was designed for pirates.

    What's Pirate for "no"? "Nar"?

    Noone has ever heard a pirate say no, pirates are positive people.

  • Marijn (unregistered)

    string[] yes = new string[]{ "y","yes,"yep","ok", "proceed","affirmative","positive", "correct","aye","fine", "yar" };

    void DoStuff() { // shorter . if( yes.Contains(Console.ReadLine()) ) { //more random stuff. }else Usage(); }

  • Marijn (unregistered)

    string[] yes = new string[]{ "yep","ok","proceed","affirmative", "positive","correct","aye","fine","yar" };

    void doSomething() { if(yes.Contains(answer)) { //programs should be less forgiving. } }

  • luctus (unregistered)

    Why didn't this guy use an array of all the yes words and loop through them (or hash, no looping required but a pretty pathetic excuse to waste memory) so we don't have to be forced to read his stupidity.

  • pengi (unregistered) in reply to BlueKnot
    BlueKnot:
    What, no provision for "maybe"?
    Would that result in a FileNotFound? :P

Leave a comment on “Are You Sure?”

Log In or post as a guest

Replying to comment #:

« Return to Article