Common Functions, not Common Sense

  • Matteo 2012-08-08 08:05
    This looks more like C#...

    FRIST!
  • PRER 2012-08-08 08:06
    FLIRST! I T HINK THIS IS PHUNNEY
  • snoofle 2012-08-08 08:06
    So, only integers are numeric? So when I count dollars and cents, I'm not using... numbers? Huh?
  • blah 2012-08-08 08:08
    The uppercase method names gives a clue as to it being C# and not Java.
  • Cbuttius 2012-08-08 08:09
    so the real WTF a usual is that people write far too much code to do string parsing, usually because the library doesn't directly support every case you wish to manage.

    Might not be the best way to do these but they probably filled a purpose needed at the time to get up and running fast.

    Putting them into a separate generic place is a good idea, perhaps StringParsingFunctins might be a better one.

    Java was always poor at string parsing unless your string is exactly the "one and only" match for the type.

  • Dave 2012-08-08 08:15
    It's C#. Main clue being that there's no such type as a "bool" in Java (in Java it's "boolean")
  • Infinite Time and Space 2012-08-08 08:16
    There is no WTF here. These functions give you flexibility to handle cases that apply to your situation that the built-ins may not have. Putting them in one class supports easy refactoring. Also, this is a common and reasonable solution when the best available programmer is someone unfamiliar with all of the built in functions of a language. We get paid to get a good enough job done as efficiently as possible. Writing the world's greatest code is often contrary to that. The side effect is that experienced programmers often have to go in and clean up someone else's mess to add new features that the original planners could not have possibly foreseen. It is what we are paid to do. Deal with it or pick another career.
  • Some Jerk 2012-08-08 08:26
    Cbuttius:
    so the real WTF a usual is that people write far too much code to do string parsing, usually because the library doesn't directly support every case you wish to manage.

    Might not be the best way to do these but they probably filled a purpose needed at the time to get up and running fast.

    Putting them into a separate generic place is a good idea, perhaps StringParsingFunctins might be a better one.

    Java was always poor at string parsing unless your string is exactly the "one and only" match for the type.



    no... TRWTF is that everything he wrote is supported directly by the string library (except that null string thing). The null string thing can be handled like this:
    var someVal = stringArg ?? "";
    basically... this fool needed to look busy so he set about reinventing the wheel day in and day out. I suppose it beats spending all day on wtf.com :p
  • Some Jerk 2012-08-08 08:27
    Some Jerk:
    Cbuttius:
    so the real WTF a usual is that people write far too much code to do string parsing, usually because the library doesn't directly support every case you wish to manage.

    Might not be the best way to do these but they probably filled a purpose needed at the time to get up and running fast.

    Putting them into a separate generic place is a good idea, perhaps StringParsingFunctins might be a better one.

    Java was always poor at string parsing unless your string is exactly the "one and only" match for the type.



    no... TRWTF is that everything he wrote is supported directly by the string library (except that null string thing). The null string thing can be handled like this:
    var someVal = stringArg ?? "";
    basically... this fool needed to look busy so he set about reinventing the wheel day in and day out. I suppose it beats spending all day on wtf.com :p
    -- string library = bad choice of words.

    double.TryParse(...) and other such interfaces make adequet substitutions as well.
  • Some Jerk 2012-08-08 08:30
    Infinite Time and Space:
    There is no WTF here. These functions give you flexibility to handle cases that apply to your situation that the built-ins may not have. Putting them in one class supports easy refactoring. Also, this is a common and reasonable solution when the best available programmer is someone unfamiliar with all of the built in functions of a language. We get paid to get a good enough job done as efficiently as possible. Writing the world's greatest code is often contrary to that. The side effect is that experienced programmers often have to go in and clean up someone else's mess to add new features that the original planners could not have possibly foreseen. It is what we are paid to do. Deal with it or pick another career.


    True... but implicit with the role of programmer is a subtle expectation of having at least some degree of common sense.

    Captcha: transverbero - a verb that looks one way but goes another.
  • Bob 2012-08-08 08:34
    I agree with Mr. Time and Space here. Code monkeys, as a breed, are far too eager to start shooting down everybody else's thinking. I believe it's because a lot of us have insecurities about our own abilities and by shooting first all the time it deflects attention from our own weaknesses and makes us feel better about ourselves. It's the one part of this field that really irks me. It's in other fields, too, but it seems to be rampant around programming in general.
  • Some Jerk 2012-08-08 08:35
    Dave:
    It's C#. Main clue being that there's no such type as a "bool" in Java (in Java it's "boolean")


    c/c++ use bool ;P... though member signatures are different.
  • Bob 2012-08-08 08:35
    That's exactly what I was talking about in my last post. This person did something slightly different than I would have, therefore they are a complete idiot devoid of any common sense whatsoever. Wow - get over yourself dude.
  • Esse 2012-08-08 08:50
    I like the fact that -12 somehow isn't numeric.
  • Some Jerk 2012-08-08 08:50
    Bob:
    That's exactly what I was talking about in my last post. This person did something slightly different than I would have, therefore they are a complete idiot devoid of any common sense whatsoever. Wow - get over yourself dude.


    you are taking this quite personally. You rename a handful of CLR functions in your past? :p

    So this isn't a WTF like an infinate recursion loop... but there is nothing wrong with laughing at someone for basically renaming library functions or writing inferior ones to use in place of those that are built in.
  • Bill Coleman 2012-08-08 08:56
    Someone should have taught this guy how to use temporary variables:

    string trimmedValue = value.ToString().Trim();

    But the level of paranoia is really high.
  • Some Jerk 2012-08-08 09:03
    What I find truly frightening is this


    public static string ReturnEmptyStringIfNullElseValue(string value)

    {
    // here is my null check
    if (value == null)

    {

    return "";

    }

    else

    {
    // MY PARAMETER, which is strongly typed as a string
    // IS NOT NULL, so now I just need to make sure it is
    // STILL A STRING!
    return value.ToString().Trim();

    }

    }

  • Severity One 2012-08-08 09:23
    Some Jerk:
    no... TRWTF is that everything he wrote is supported directly by the string library (except that null string thing). The null string thing can be handled like this:
    var someVal = stringArg ?? "";
    basically... this fool needed to look busy so he set about reinventing the wheel day in and day out. I suppose it beats spending all day on wtf.com :p
    Ah, so that's why, because I'm using an empty-string-instead-of-null method in the Java application I wrote and that I happened to be looking at a few minutes ago. Java can get pedantic with null pointer exceptions, and it doesn't have a similar construct.
  • ullamcorper 2012-08-08 09:30
    I find it funny how close to python code the method name "ReturnEmptyStringIfNullElseValue" is.

    def ReturnEmptyStringIfNullElseValue(value):
    
    return "" if not value else value

    In: ReturnEmptyStringIfNullElseValue(None)
    Out: ''

    In: ReturnEmptyStringIfNullElseValue("value")
    Out: 'value'
  • the beholder 2012-08-08 09:30
    Bob:
    I agree with Mr. Time and Space here. Code monkeys, as a breed, are far too eager to start shooting down everybody else's thinking. I believe it's because a lot of us have insecurities about our own abilities and by shooting first all the time it deflects attention from our own weaknesses and makes us feel better about ourselves. It's the one part of this field that really irks me. It's in other fields, too, but it seems to be rampant around programming in general.
    You should abandon programming STAT and enter sociology. That way everyone would be happy: you would be paid to analyze people and we would be subjected to less posts where someone defends a programmer who clearly either didn't know what he was doing or didn't think things through. And also we would only get a socio-anthropological analysis of why we do what we do when we want it.

    And I should become a career counselor :)
  • Spivonious 2012-08-08 09:33
    I don't see a WTF in the first method. I have one of those myself (in VB.NET, where there is no ?? operator). Of course, you could write it with the ?? operator, but not too many people know about that one.

    edit - I now know that I can use the If() method in those cases. You learn something new everyday.


    As far as the others, what is the built-in function for removing $ and , from strings to get an integer value?

    I'll give you a WTF for the IsNumeric function. If he didn't want to use TryParse, then he could have included the VB library and called VB's old IsNumeric function.
  • Remy Porter 2012-08-08 09:44
    The lack of a ternary operator is one of my biggest pet peeves in VB. That and the general lack of operator overloading.
  • Marlon 2012-08-08 09:52
    UNICORNS!!!!!

    *edit, no this is not spam...
  • Spivonious 2012-08-08 09:52
    Remy Porter:
    The lack of a ternary operator is one of my biggest pet peeves in VB. That and the general lack of operator overloading.


    int i = a < b ? 1 : 2;
    Dim i = If(a < b, 1, 2)

    Public Shared Operator +(lhs As Integer, rhs As Integer) As Integer
    Return lhs + rhs
    End Operator
  • Remy Porter 2012-08-08 09:56
    If() is computationally the same as the ternary operator, but it is not a ternary operator. The ternary operator is cleaner in terms of syntax, in my opinion.
  • the beholder 2012-08-08 09:56
    hey, if this is a Remy post were are the HTML comments? Unicorns are not enough, you should now that Remy
  • Not an enterprise code monkey 2012-08-08 09:58
    You can do this in one line in Haskell
  • Remy Porter 2012-08-08 10:02
    It's a little hard to insert good HTML comments in a CodeSOD.
  • One Coder, One Cattle Prod 2012-08-08 10:02
    Seriously? I'm a tester (OK, an SDET) and even I know that C# has a null coalescing operator. Any developer who can't even be bothered to familiarise themselves with simple features of their chosen language needs to get a new job. I hear the helpdesk are hiring.
  • Matt 2012-08-08 10:05
    maybe string.IsNullOrEmpty() did not occur to him.
  • Loren Pechtel 2012-08-08 10:13
    Spivonious:
    I don't see a WTF in the first method. I have one of those myself (in VB.NET, where there is no ?? operator). Of course, you could write it with the ?? operator, but not too many people know about that one.

    edit - I now know that I can use the If() method in those cases. You learn something new everyday.


    As far as the others, what is the built-in function for removing $ and , from strings to get an integer value?

    I'll give you a WTF for the IsNumeric function. If he didn't want to use TryParse, then he could have included the VB library and called VB's old IsNumeric function.


    There are redundant ToString() calls throughout the code. There's also a fear of having a local copy of the data you're working on.

    The only WTF I see is the duplication of IsNumeric(). Everything else is simply inefficient but unlike what some posters have said it does *NOT* simply redo the library.
  • Bob 2012-08-08 10:17
    Some Jerk:
    Bob:
    That's exactly what I was talking about in my last post. This person did something slightly different than I would have, therefore they are a complete idiot devoid of any common sense whatsoever. Wow - get over yourself dude.


    you are taking this quite personally. You rename a handful of CLR functions in your past? :p

    So this isn't a WTF like an infinate recursion loop... but there is nothing wrong with laughing at someone for basically renaming library functions or writing inferior ones to use in place of those that are built in.


    I'm just saying it would be more productive if people could point out the flaws of others without having to call them idiots or morons. I mean, I could sit here say "you're an idiot because you can't spell the word infinite" but it would be more constructive to stay focused on the correct way of doing it and not wasting time denigrating the person that you are trying to correct. Too many people act as though they have *never* made a mistake or done something in a less-than-optimal way, which is ridiculous.
  • just me 2012-08-08 10:34
    Bob:

    I'm just saying it would be more productive if people could point out the flaws of others without having to call them idiots or morons. I mean, I could sit here say "you're an idiot because you can't spell the word infinite" but it would be more constructive to stay focused on the correct way of doing it and not wasting time denigrating the person that you are trying to correct. Too many people act as though they have *never* made a mistake or done something in a less-than-optimal way, which is ridiculous.


    +1

    btw, how's your son?
  • Cbuttius 2012-08-08 10:35
    From an immediate viewpoint the only one that really looks WTF'y is the last one.

    I'm a C++ programmer and don't know C# and how those functions are total rewrites. It's difficult to know exactly what they are doing anyway. What are all these '$' signs doing there? Parsing amounts of money?

    I'm sure the C# library has much better string parsing options than C++ (istringstream, oh dear is that the best we can do? boost::lexical_cast wrapper of that throwing unhelpful exception when it fails..)

    Now let me explain a concept: objects get printed to strings. But strings don't get loaded into empty objects, strings are parsed by factories which create objects. And it isn't a one-to-one relationship in either direction.

    Incidentally the lack of a hexadecimal point is a WTF in C++ and C# although I think C99 supports it.
  • Craig 2012-08-08 11:04
    By my recollection the TryParse() methods were not introduced until .NET 2.0. For all we know this code was written in .NET 1.0 or 1.1, in which case you pretty much had to roll your own IsNumeric (unless you leveraged the Microsoft.VisualBasic namespace, which I personally preferred not to do).

    The real WTF is that developers never take into account under what circumstances the code was written. Maybe the developer was using an older version, maybe his boss was hounding him to "just get it done."

    There are plenty of things in this business to make fun of, but these examples aren't as egregious as the story makes them out to be.
  • default_ex 2012-08-08 11:10
    That first function is horrendously over complicated for what it says it does.

    notNullString = ReturnEmptyStringIfNullElseValue(someString);

    notNullString = someString ?? string.Empty;

    Now it might just be because I actually know the language, but I find the second version much more readable.
  • Rob 2012-08-08 11:14
    Also, its a function, so both arguments will be evaluated.

    In C# you can write:

    (a == 1) ? b() : c();

    In VB

    IIf(a = 1, b(), c())

    will call both b() and c(), but only return one result!
  • Tuka 2012-08-08 11:17
    The given functions are not perfect. But there is no WTF. The writer of that code might lack experience or tuition. Anyway, the code shall work, is readable and not horrible inefficient.

    Since that the real WTF is the fellow 'Ben'. His mention those examples as WTF is an proof that Ben is a arrogant, autocratic goof.

    A self-opinionated mind is one of the saves ways into programers hell.
  • Wonk 2012-08-08 11:19
    just me:
    Bob:

    I'm just saying it would be more productive if people could point out the flaws of others without having to call them idiots or morons. I mean, I could sit here say "you're an idiot because you can't spell the word infinite" but it would be more constructive to stay focused on the correct way of doing it and not wasting time denigrating the person that you are trying to correct. Too many people act as though they have *never* made a mistake or done something in a less-than-optimal way, which is ridiculous.


    +1

    btw, how's your son?


    I'm sure it's no laughing matter.
  • Your Name 2012-08-08 11:27
    Java/C# With First Letter Of Function Capatalized. Twitch.

    NOOOOOOOOOOOOOOOOOOOOOOOOOOOOOoooooooooooooooooooooooooooooo.............
  • Cbuttius 2012-08-08 11:49
    Ok, an obvious WTF is calling value.ToString() when value is already a string. I assume that all classes inherit from Object() and must have a ToString() method so string also has one, which probably just is implemented as "return this;"

    It is quite common in C++ too to have a template to convert things to string and then provide an overload / specialization for strings. At least in C# you don't have the WTF'ery of having to deal with two types of character that might form a string.

    Incidentally in C++ if you do this

    template< typename T >
    T parse( std::string const& str )
    {
    std::istringstream iss( str );
    T t;
    iss >> t; // yeah handle errors etc.
    return t;
    }

    It is not just inefficient for T=std::string, it doesn't work properly..

    std::string hw( "Hello world" );
    std::string parsed = parse<std::string>(hw);

    and parsed will be just "Hello"

    Doing this for a large array of ints is bad too in that you create a stringbuf for every single one and don't reuse it.

  • pantsman 2012-08-08 11:57
    default_ex:
    notNullString = ReturnEmptyStringIfNullElseValue(someString);

    notNullString = someString ?? string.Empty;


    What if this code was written before nullable types were added to the language?
  • nisl 2012-08-08 12:01
    ullamcorper:
    I find it funny how close to python code the method name "ReturnEmptyStringIfNullElseValue" is.

    def ReturnEmptyStringIfNullElseValue(value):
    
    return "" if not value else value

    In: ReturnEmptyStringIfNullElseValue(None)
    Out: ''

    In: ReturnEmptyStringIfNullElseValue("value")
    Out: 'value'



    It's better not to program than to program in that jiberish.
  • Some Jerk 2012-08-08 12:03
    Bob:
    Some Jerk:
    Bob:
    That's exactly what I was talking about in my last post. This person did something slightly different than I would have, therefore they are a complete idiot devoid of any common sense whatsoever. Wow - get over yourself dude.


    you are taking this quite personally. You rename a handful of CLR functions in your past? :p

    So this isn't a WTF like an infinate recursion loop... but there is nothing wrong with laughing at someone for basically renaming library functions or writing inferior ones to use in place of those that are built in.


    I'm just saying it would be more productive if people could point out the flaws of others without having to call them idiots or morons. I mean, I could sit here say "you're an idiot because you can't spell the word infinite" but it would be more constructive to stay focused on the correct way of doing it and not wasting time denigrating the person that you are trying to correct. Too many people act as though they have *never* made a mistake or done something in a less-than-optimal way, which is ridiculous.


    Obviously. And I enjoy very much ... mocking my own stupidity every opportunity I get. Spelling is usually my problem however... and it has lead to some rather funny situations involving application wide updates and renames. Flatulantly for me... Microsoft added some safeguards for just such an eventuality.

    I suppose I don't remember calling anyone an idiot on this thread however.

    Someone wrote that the user was not substituting pre-existing functionality... and I argue that every method was a substitution of pre-existing syntax and/or built in library methods. So hurry up and (CAPTCHA: AUGUE) with me.
  • nisl 2012-08-08 12:04
    One Coder, One Cattle Prod:
    Seriously? I'm a tester (OK, an SDET) and even I know that C# has a null coalescing operator. Any developer who can't even be bothered to familiarise themselves with simple features of their chosen language needs to get a new job. I hear the helpdesk are hiring.


    Usually bozos like that are not qualified for ANY IT job.
  • no laughing matter 2012-08-08 12:09
    Craig:
    By my recollection the TryParse() methods were not introduced until .NET 2.0. For all we know this code was written in .NET 1.0 or 1.1, in which case you pretty much had to roll your own IsNumeric (unless you leveraged the Microsoft.VisualBasic namespace, which I personally preferred not to do).

    The real WTF is that developers never take into account under what circumstances the code was written. Maybe the developer was using an older version, maybe his boss was hounding him to "just get it done."

    There are plenty of things in this business to make fun of, but these examples aren't as egregious as the story makes them out to be.

    Please use the established meme:
    I don't see what's wrong with this code! Does anyone of you bitches know the specs?
  • C-Derb 2012-08-08 12:10
    Cbuttius:
    Ok, an obvious WTF is calling value.ToString() when value is already a string.

    +100
    I get that sometimes you may write code only to realize later that there is something similar built into the language. And I agree that all we are presented with is the code and no context to when it was written and what was built into the framework at the time.

    But calling string.ToString() is indefensible. Whiskey. Tango. Foxtrot.
  • nisl 2012-08-08 12:10
    Craig:
    By my recollection the TryParse() methods were not introduced until .NET 2.0. For all we know this code was written in .NET 1.0 or 1.1, in which case you pretty much had to roll your own IsNumeric (unless you leveraged the Microsoft.VisualBasic namespace, which I personally preferred not to do).

    The real WTF is that developers never take into account under what circumstances the code was written. Maybe the developer was using an older version, maybe his boss was hounding him to "just get it done."

    There are plenty of things in this business to make fun of, but these examples aren't as egregious as the story makes them out to be.


    He was using TryParse methods, therefore he was using at least 2.0.

    I can see entering .NET using VB, but sticking with it after 10 fucking years of development is just plain stupid - even if the company can't or doesn't allow the switch (move the fuck on). If you're still with VB.NET, you are a moron and incompetent programmer by definition.

    "Just get it done" attitude would need to result in inline "if null set "" else set value" pattern - versus writing some confusingly named and what-the-fuck-that-this-function-really-do-let-me-look-it-up-every-time-cause-it-is-impossible-to-remember-ever functions.

    What other excuses can you think of?
  • Dave2 (seriously) 2012-08-08 12:10
    Also, the "out" keyword is only used in C# I believe. Not java or c/c++.
  • no laughing matter 2012-08-08 12:13
    Wonk:
    just me:
    Bob:

    ...


    +1

    btw, how's your son?


    I'm sure it's no laughing matter.

    Wrong!

    Stated it before and will state it again: Bob and i are not related!

    Neither am i his son nor is he my uncle!
  • myName 2012-08-08 12:15
    He didn't use something that was introduced after he wrote the program - isn't he a fool.

    Seriously, give use the date the original was written when you're posting WTFs like this.
  • no laughing matter 2012-08-08 12:41
    To all of you defending this code: Learn to program proper!

    This codebase is a huge W-T-clusterFuck.

    1.) Violation of separation-of-concerns / single-responsibility-principle. Implementing too many functionality in each method.
    2.) Misleading method names: "ReturnEmptyStringIfNullElseValue" does not return the value, it returns the trimmed value.
    3.) Violation of Don't-Repeat-Yourself all over the place. Why the animosity against temporary / local variables? And that replace-code is repeated all over again instead of put into a separate method.
    4.) What's the point of first parsing as Int and if that fails, parsing as Decimal? Why not parse it as decimal from the beginning?
    5.) Other WTfs already pointed out: Calling ToString() on a string, inefficient coding: using Substring instead of an indexer to retrieve a single Char from a String.
    6.) What's the idea of accepting input data and convert it into a number even if it is not a number? One might accept the idea that a money input may be in the form "$123.45", but this code will also accept ",7$56$,18.$9". This is worse than PHP!

  • Ben Jammin 2012-08-08 12:46
    Craig:
    By my recollection the TryParse() methods were not introduced until .NET 2.0. For all we know this code was written in .NET 1.0 or 1.1, in which case you pretty much had to roll your own IsNumeric (unless you leveraged the Microsoft.VisualBasic namespace, which I personally preferred not to do).

    The real WTF is that developers never take into account under what circumstances the code was written. Maybe the developer was using an older version, maybe his boss was hounding him to "just get it done."

    There are plenty of things in this business to make fun of, but these examples aren't as egregious as the story makes them out to be.


    This was my initial assumption on the matter. It has been a while since I've played in 1.1, so I don't remember everything it lacked, but as the guy who wrote the code is supposedly retiring, I don't doubt he had old libraries.
  • Some Jerk 2012-08-08 12:46
    nisl:
    Craig:
    By my recollection the TryParse() methods were not introduced until .NET 2.0. For all we know this code was written in .NET 1.0 or 1.1, in which case you pretty much had to roll your own IsNumeric (unless you leveraged the Microsoft.VisualBasic namespace, which I personally preferred not to do).

    The real WTF is that developers never take into account under what circumstances the code was written. Maybe the developer was using an older version, maybe his boss was hounding him to "just get it done."

    There are plenty of things in this business to make fun of, but these examples aren't as egregious as the story makes them out to be.


    He was using TryParse methods, therefore he was using at least 2.0.

    I can see entering .NET using VB, but sticking with it after 10 fucking years of development is just plain stupid - even if the company can't or doesn't allow the switch (move the fuck on). If you're still with VB.NET, you are a moron and incompetent programmer by definition.

    "Just get it done" attitude would need to result in inline "if null set "" else set value" pattern - versus writing some confusingly named and what-the-fuck-that-this-function-really-do-let-me-look-it-up-every-time-cause-it-is-impossible-to-remember-ever functions.

    What other excuses can you think of?


    Ummm... where is all this commentary about basic coming from? That was c# code in the story.

    Finally... as to your ignorant comment... well... all I can say is that the coder makes the app, not the language. VB and c# are both converted to clr, and both compiled to run on .NET framework. The result is dictated by the imagination and knowledge of whomever wrote the code... so how that code was expressed carries no relavence whatsoever. My suggestion would be to use whichever language one is comfortable with. I choose c# (when I have a choice) because the syntax is more commonly held across multiple languages, and I have used many. But one who claims that VB or those who use it are in some way intellectually deficient is clearly someone who speaks without knowledge.
  • JoeCool 2012-08-08 12:51
    Severity One:
    Ah, so that's why, because I'm using an empty-string-instead-of-null method in the Java application I wrote and that I happened to be looking at a few minutes ago. Java can get pedantic with null pointer exceptions, and it doesn't have a similar construct.


    Java similar construct:

    String someVal = stringArg == null ? "" : stringArg;
  • tom 2012-08-08 13:09
    blah:
    The uppercase method names gives a clue as to it being C# and not Java.

    Actually, the first non-blank line suggests it. It says string, not String.
  • n_slash_a 2012-08-08 13:27
    Apparently -10, 0xA, and 1e1 are all not numbers. One could also make a case about 10.0, but that depends on if your definition of numeric includes floats or just integers.
  • AGray 2012-08-08 13:36
    I'll take a crack at a Java isNumeric() function:

    public bool isNumeric(string value)
    
    {
    try
    {
    int ignored = Integer.parseInt(value);
    }
    catch
    {
    return false;
    }

    return true;
    }


    ...Maybe I'm overthinking this...
  • rawling 2012-08-08 13:47
    Throw/catching exceptions in non-exceptional cases: good job.
  • default_ex 2012-08-08 13:52
    pantsman:
    default_ex:
    notNullString = ReturnEmptyStringIfNullElseValue(someString);

    notNullString = someString ?? string.Empty;


    What if this code was written before nullable types were added to the language?


    Moot point, the original function checks for "== null". The example I posted would be expanded by the compiler into:

    if (someString == null)
    notNullString = string.Empty;
    else
    notNullString = someString;
  • newbie to site 2012-08-08 14:09
    Loren Pechtel:
    Spivonious:
    I don't see a WTF in the first method. I have one of those myself (in VB.NET, where there is no ?? operator). Of course, you could write it with the ?? operator, but not too many people know about that one.

    edit - I now know that I can use the If() method in those cases. You learn something new everyday.


    As far as the others, what is the built-in function for removing $ and , from strings to get an integer value?

    I'll give you a WTF for the IsNumeric function. If he didn't want to use TryParse, then he could have included the VB library and called VB's old IsNumeric function.


    There are redundant ToString() calls throughout the code. There's also a fear of having a local copy of the data you're working on.

    The only WTF I see is the duplication of IsNumeric(). Everything else is simply inefficient but unlike what some posters have said it does *NOT* simply redo the library.


    Not to beat on a dead horse, but I just love the string.ToString because the 'string' might mysteriously convert itself to some other type. Let's add another one to the library of functions:

    Public Static string GetString(string str)
    { return str.ToString() }
  • Nagesh 2012-08-08 15:34
    This ain't being necesary as Java having no null check on parse of Integar from String for performing reason.
    String str = "13";
    
    int n = -1;
    try {
    n = Integer.parseInt();
    catch (NumberFormatException ex) {}
    catch (NullPointerException ex) {}
    return n >= 0;


    This is meking Nagesh mother cry.
  • Bob 2012-08-08 16:01
    Nagesh:
    This ain't being necesary as Java having no null check on parse of Integar from String for performing reason.
    String str = "13";
    
    int n = -1;
    try {
    n = Integer.parseInt();
    catch (NumberFormatException ex) {}
    catch (NullPointerException ex) {}
    return n >= 0;


    This is meking Nagesh mother cry.


    Somebody tell Nagesh to stop showing mother the code !
  • dogmatic 2012-08-08 16:16
    This reminds me of that George Carlin joke about speeding...
    "Anybody who knows less about programming than me is an idiot. Anybody who knows more about programming than me is a maniac!"
  • silly 2012-08-08 16:20
    In the function ReturnDecimalValueOfString(string value) where is OM declared?

    In the function isNumeric(string value) at the very least
    why use value.Substring(i, 1) as opposed to value(i);
    why not break out of the loop:
    for (int i = 0; i < value.Length; i++)
    {
    if (!"1234567890".Contains(value.Substring(i, 1)))
    {
    isNum = false;
    //EXIT FOR;
    //or this
    //i = value.Length;
    }
    }
  • oops 2012-08-08 16:36
    silly:
    In the function ReturnDecimalValueOfString(string value) where is OM declared?


    That's a Zero, not an O as in Omega.
    It's a numeric constant, M suffix designates Decimal.
  • now and then 2012-08-08 16:39
    I have not seen this mentioned yet. In the 'ReturnIntValueOfString' function I would have handled the decimal portion by trimming it as so:

    if(value.IndexOf(".") > -1) {value=value.Substring(0,value.IndexOf("."));}
  • Somebody 2012-08-08 16:44
    Rob:
    Also, its a function, so both arguments will be evaluated.

    In C# you can write:

    (a == 1) ? b() : c();

    In VB

    IIf(a = 1, b(), c())

    will call both b() and c(), but only return one result!


    There's a (rather large) difference between IIF() and if() in VB.Net (3.5 or 4 ... can't remember)
    Plus if() can also do the C# ?? operator if using the two argument version.

    if(boolean expression, A, B)
    if(X,Y)
    both exists in VB.Net now.

    Always easier to find flaws in *other* peoples code.
  • PRMan 2012-08-08 17:20
    silly:
    In the function ReturnDecimalValueOfString(string value) where is OM declared?

    In the function isNumeric(string value) at the very least
    why use value.Substring(i, 1) as opposed to value(i);
    why not break out of the loop:
    for (int i = 0; i < value.Length; i++)
    {
    if (!"1234567890".Contains(value.Substring(i, 1)))
    {
    isNum = false;
    //EXIT FOR;
    //or this
    //i = value.Length;
    }
    }


    Or just "return false;"
  • Jimmy 2012-08-08 18:26
    Severity One:
    Some Jerk:
    no... TRWTF is that everything he wrote is supported directly by the string library (except that null string thing). The null string thing can be handled like this:
    var someVal = stringArg ?? "";
    basically... this fool needed to look busy so he set about reinventing the wheel day in and day out. I suppose it beats spending all day on wtf.com :p
    Ah, so that's why, because I'm using an empty-string-instead-of-null method in the Java application I wrote and that I happened to be looking at a few minutes ago. Java can get pedantic with null pointer exceptions, and it doesn't have a similar construct.
    Surely in Java you can say something like
    String fredBob = ((Jim==NULL)?"":Jim);

  • a;eowri 2012-08-08 18:38
    AGray:
    I'll take a crack at a Java isNumeric() function:

    public bool isNumeric(string value)
    
    {
    try
    {
    int ignored = Integer.parseInt(value);
    }
    catch
    {
    return false;
    }

    return true;
    }


    ...Maybe I'm overthinking this...

    Would it work for NaN? would it work for null?
    Staring way too long, and scratching on my skull.
    A string is not a number, and a number not a string,
    so functions to convert...who needed such a thing?
  • Yousah 2012-08-08 18:41
    a;eowri :
    AGray:
    I'll take a crack at a Java isNumeric() function:

    public bool isNumeric(string value)
    
    {
    try
    {
    int ignored = Integer.parseInt(value);
    }
    catch
    {
    return false;
    }

    return true;
    }


    ...Maybe I'm overthinking this...

    Would it work for NaN? would it work for null?
    Staring way too long, and scratching on my skull.
    A string is not a number, and a number not a string,
    so functions to convert...who needed such a thing?
    Indeed:

    bool isNumeric(String s)
    {
    return false;
    }
  • Some Jerk 2012-08-08 18:51
    a;eowri :
    AGray:
    I'll take a crack at a Java isNumeric() function:

    public bool isNumeric(string value)
    
    {
    try
    {
    int ignored = Integer.parseInt(value);
    }
    catch
    {
    return false;
    }

    return true;
    }


    ...Maybe I'm overthinking this...

    Would it work for NaN? would it work for null?
    Staring way too long, and scratching on my skull.
    A string is not a number, and a number not a string,
    so functions to convert...who needed such a thing?


    This is a joke or are you genuinely curious?

    If you really need it explained, perhaps it would make more sense if I told you that 5 and 53 can be represented by the same value :p.

    Numerically, 53 is a standard integer that can fit in a 1 byte (8 bit) space. If (however) I say ((char)53) then I end up with a '5'.

    As people typically enter numbers in the form of text (and not the way that number looks in memory)... int.Parse( "5" ); would yield the number 5 while (int)"5"[0] would yield 53. If the user enters 5 in a text box, I am grabbing that as a string and would prefer to covert it to the number 5 instead of the number 53... seems a tad more accurate.
  • Veldan 2012-08-08 20:25
    I had a very similar mess to work with where out coders had decided that all database functions for ALL classes should be kept in the "DatabaseCommon" file and the SQL that those database calls use should be retrieved from "DatabaseCommonSQL" functions...

    Yeah it was fun fixing that :S

    As to the string being null or empty, VB.net covers that nicely:

    Return IIf(String.IsNullOrEmpty(value), "", value)
  • AnonymousCoder 2012-08-08 22:04
    Ya know, I'm starting to see a pattern here... What I mean is, it looks like these type of "programmers" seem to exhibit the same coding habits. I happen (to have the misfortune !) to work in the company of a couple of them geniuses too, although not as pathetic as the hero of this article.

    Anyway - seems like they all like to abuse string arithmetic! Trim() is their most popular, along with Contains(), Upper(), Split() and last but not least - Substring(). Another "feature" of their code is conversion of basic types to string and back. One of my guys once told me that (quote) "the string is the most user-friendly type in the world"...
  • AnonymousCoder 2012-08-08 22:13
    I think I'll post some gems on WTF.com too.
    The author of this article mentioned that the Functions class had "thousands-of-lines", which made me remember the cold reality that I'm in.
    I've got a class with 10,000 (that's right, TEN THOUSANDS) lines, and growing.
    Wait till I show you what's in there ! It's a horror story !
  • Meep 2012-08-08 23:44
    Remy Porter:
    The lack of a ternary operator is one of my biggest pet peeves in VB. That and the general lack of operator overloading.


    Funny, I hardly ever use Python's ternary operator. If something is "something_positive or default" I just use "or", once I've written "foo if this else bar", I find I want to break it out into a proper block anyway.

    Why do you want operator overloading (or did you mean short-circuiting?) in VB? VB has bog-simple semantics by design: it's BASIC for crying out loud.
  • Milde 2012-08-09 00:16
    AnonymousCoder:
    I think I'll post some gems on WTF.com too.
    The author of this article mentioned that the Functions class had "thousands-of-lines", which made me remember the cold reality that I'm in.
    I've got a class with 10,000 (that's right, TEN THOUSANDS) lines, and growing.
    Wait till I show you what's in there ! It's a horror story !
    I jusr can't wait....and unless you posted it last week, it probably won't happen in my lifetime...
  • not a;eowri 2012-08-09 00:17
    Some Jerk:
    a;eowri :
    AGray:
    I'll take a crack at a Java isNumeric() function:

    public bool isNumeric(string value)
    
    {
    try
    {
    int ignored = Integer.parseInt(value);
    }
    catch
    {
    return false;
    }

    return true;
    }


    ...Maybe I'm overthinking this...

    Would it work for NaN? would it work for null?
    Staring way too long, and scratching on my skull.
    A string is not a number, and a number not a string,
    so functions to convert...who needed such a thing?


    This is a joke or are you genuinely curious?

    If you really need it explained, perhaps it would make more sense if I told you that 5 and 53 can be represented by the same value :p.

    Numerically, 53 is a standard integer that can fit in a 1 byte (8 bit) space. If (however) I say ((char)53) then I end up with a '5'.

    As people typically enter numbers in the form of text (and not the way that number looks in memory)... int.Parse( "5" ); would yield the number 5 while (int)"5"[0] would yield 53. If the user enters 5 in a text box, I am grabbing that as a string and would prefer to covert it to the number 5 instead of the number 53... seems a tad more accurate.
    Hmmm.....looks genuinely serious to me....
  • Jon Haugsand 2012-08-09 02:24
    no laughing matter:
    To all of you defending this code: Learn to program proper!

    This codebase is a huge W-T-clusterFuck.

    1.) Violation of separation-of-concerns / single-responsibility-principle. Implementing too many functionality in each method.
    2.) Misleading method names: "ReturnEmptyStringIfNullElseValue" does not return the value, it returns the trimmed value.
    3.) Violation of Don't-Repeat-Yourself all over the place. Why the animosity against temporary / local variables? And that replace-code is repeated all over again instead of put into a separate method.
    4.) What's the point of first parsing as Int and if that fails, parsing as Decimal? Why not parse it as decimal from the beginning?
    5.) Other WTfs already pointed out: Calling ToString() on a string, inefficient coding: using Substring instead of an indexer to retrieve a single Char from a String.
    6.) What's the idea of accepting input data and convert it into a number even if it is not a number? One might accept the idea that a money input may be in the form "$123.45", but this code will also accept ",7$56$,18.$9". This is worse than PHP!



    Bad coding, yes, but hardly a WTF.

    /Jon
  • Cbuttius 2012-08-09 05:33
    no laughing matter:
    To all of you defending this code:
    This codebase is a huge W-T-clusterFuck.

    1.) Violation of separation-of-concerns / single-responsibility-principle. Implementing too many functionality in each method.

    I can't see that here. Each method is doing one job of parsing a string. That the outer class is called "Functions" and not "String conversion functions" or whatever is part of the language WTF of C# (and Java) not allowing free-functions (ideally in extendable namespaces) and forcing you to put everything in a class.

    2.) Misleading method names: "ReturnEmptyStringIfNullElseValue" does not return the value, it returns the trimmed value.

    Slightly misleading yes and verbose but not totally misleading as trimming is part of the logic.

    3.) Violation of Don't-Repeat-Yourself all over the place. Why the animosity against temporary / local variables? And that replace-code is repeated all over again instead of put into a separate method.

    Probably if it should be there at all and if there's a good way to refactor it.

    4.) What's the point of first parsing as Int and if that fails, parsing as Decimal? Why not parse it as decimal from the beginning?

    There can be a point sometimes in doing this, if most of your input is ints and the int parsing is a lot faster then it is an efficiency.

    5.) Other WTfs already pointed out: Calling ToString() on a string, inefficient coding: using Substring instead of an indexer to retrieve a single Char from a String.

    Of course in C++ you get a char from a string with a straight-forward []. C# and Java don't like to see strings as a sequence of chars but what the hell else are they? Of course we know that in UTF-8 not every logical character is a single char but I don't think that's any different in Java and C#.

    6.) What's the idea of accepting input data and convert it into a number even if it is not a number? One might accept the idea that a money input may be in the form "$123.45", but this code will also accept ",7$56$,18.$9". This is worse than PHP!

    Would come under the C++ definition of "undefined behaviour" where the compiler / system is not enforced to have a fixed behaviour when you do an illegal operation. If you input garbage you get "undefined behaviour" here in that it might process it or might not. In reality you won't ever get that input and if you treat it as an UB situation it is not a WTF.

    Learn to program proper!


    I am sure if I had to solve this situation in a language that is not my own I would have avoided some of the WTFs there but my code probably wouldn't be that great.

    The real WTF though is that your comment got featured while none of my comments on the C++ WTF we had a week or two ago got featured, in fact Alex decided to have a day off featuring comments on that WTF. It's a WTF that Alex never featuers any of my comments and I will continue to moan about it on here every day until he does.

  • Severity One 2012-08-09 06:20
    Jimmy:
    Severity One:
    Ah, so that's why, because I'm using an empty-string-instead-of-null method in the Java application I wrote and that I happened to be looking at a few minutes ago. Java can get pedantic with null pointer exceptions, and it doesn't have a similar construct.
    Surely in Java you can say something like
    String fredBob = ((Jim==NULL)?"":Jim);
    Well, yes, obviously, but this becomes tedious if you have to do with for several strings, and if it's not a simple variable but the return value from a method. The C# construct doesn't require the 'Jim' variable/expression twice.
  • Grzes 2012-08-09 07:05

    To all of you defending this code: Learn to program proper!

    This codebase is a huge W-T-clusterFuck.

    (...)


    I'm a programmer, not a philosopher, so I won't argue with such grandiloquent phrases as separation-of-concerns and single-responsibility-principle. I believe you are right (for most points), maybe in the Java world there is an emphasis on doing things in accordance to some specific doctrines and if it actually works is a secondary issue.

    However, I don't agree with point 5. I strongly deem that using both words "Java" and "efficiency" in one sentence is a stylistic error, because these words are simply incompatible.

    If you care about efficiency, don't use Java.
    If you use Java, don't aim for efficiency, because this is something you already lost choosing Java.
  • no laughing matter 2012-08-09 07:47
    Cbuttius:

    I can't see that here. Each method is doing one job of parsing a string.
    Let's check this:
    * ReturnEmptyStringIfNullElseValue: Convert's nulls into empty string. Trims non-null strings. Two separate functionalities.
    * ReturnIntValueOfString: Again convert's nulls into empty string and trims non-null strings. Additionally it replaces "$" and "," with "", then tries to parse as Integer, after that tries to parse as Decimal. Converts null and empty string to 0. Six separate functionalities.

    Cbuttius:

    There can be a point sometimes in doing this, if most of your input is ints and the int parsing is a lot faster then it is an efficiency.
    If efficiency was a concern, then this code fails for repeating the same operations over and over again.

    Cbuttius:

    Of course in C++ you get a char from a string with a straight-forward []. C# and Java don't like to see strings as a sequence of chars
    Wrong!

    In Java, String implements the CharSequence interface, so it definitely sees strings as a sequence as chars. It does not provide the []-operator, you have to use the charAt(int) - method.

    C# does provide the []-operator.

    Cbuttius:

    Of course we know that in UTF-8 not every logical character is a single char but I don't think that's any different in Java and C#.
    That's correct, but not relevant for the code in question, as Substring() also operates on sequences of 16Bit-characters, not Unicode codepoints.

    Cbuttius:

    Would come under the C++ definition of "undefined behaviour" where the compiler / system is not enforced to have a fixed behaviour when you do an illegal operation. If you input garbage you get "undefined behaviour" here in that it might process it or might not. In reality you won't ever get that input and if you treat it as an UB situation it is not a WTF.
    If that input data comes from user input there is no guarantee that you won't get that input (as we already know, cats like to sleep on keyboards) and the correct behaviour is to reject such erronous input.

    Cbuttius:

    I am sure if I had to solve this situation in a language that is not my own I would have avoided some of the WTFs there but my code probably wouldn't be that great.
    As others already have suggested: Use the methods / libraries that are part of the platform instead of re-inventing them poorly.

    Cbuttius:

    The real WTF though is that your comment got featured while none of my comments on the C++ WTF we had a week or two ago got featured, in fact Alex decided to have a day off featuring comments on that WTF. It's a WTF that Alex never featuers any of my comments and I will continue to moan about it on here every day until he does.

    I have also noticed that in the last weeks Alex performance in the featuring department was very poor. He seems to be trying to overcompensate for this now, so maybe in a few days he might get a better review on his core field of action from you!

    Just keep on reading yourdailyfeaturedcomment.com.
  • Some Jerk 2012-08-09 08:46
    Grzes:


    If you care about efficiency, don't use Java.
    If you use Java, don't aim for efficiency, because this is something you already lost choosing Java.


    Point of fact... yes... Java runs like an old hound with only 2 legs and a severe case of IBS on a Windows system... primarily when utilizing the UI components. This problem exists exclusively for Windows however. Running a Java app on Fedora or any Mac/Nix OS will yield much more positive results. Therefore, many people choose to use Java and manage to incorporate efficiency quite well. They are simply writing the code to execute within its' native environment.
  • Yojin 2012-08-09 08:53
    I've got a variant of ReturnIntValueOfString function in a few of my classes where I needed to do a lot of converting strings (that were often null or blank) into integers...

    Is mine a WTF?

    private static int ToIntOrZero(this string str)
    {
    if(string.IsNullOrWhiteSpace(str))
    return 0; // quick return.

    int val = 0;
    int.TryParse(str, out val);
    return val;
    }
  • Some Jerk 2012-08-09 08:55
    [quote user="Cbuttius]
    The real WTF though is that your comment got featured while none of my comments on the C++ WTF we had a week or two ago got featured, in fact Alex decided to have a day off featuring comments on that WTF. It's a WTF that Alex never featuers any of my comments and I will continue to moan about it on here every day until he does.

    [/quote]
    That is surprising to read so directly from someone. Do you ever go to your friend's house and complain that he drinks someone else's beer and never your own? This website is a lot of fun, and it is enjoyable to be vocal and all... but bottom line, this is Alex's personal space that we are privileged to share.

    I suspect that the comments that are featured are featured because Alex enjoyed reading them. I seriously doubt the name next to the post is even considered. Therefore... if getting featured means so much to you, then spend more time thinking before you post... and post something that is interesting to read.
  • Some Jerk 2012-08-09 08:57
    :( I broke it
  • Loren Pechtel 2012-08-09 10:18
    default_ex:
    That first function is horrendously over complicated for what it says it does.

    notNullString = ReturnEmptyStringIfNullElseValue(someString);

    notNullString = someString ?? string.Empty;

    Now it might just be because I actually know the language, but I find the second version much more readable.


    This does *NOT* produce the same results.

    I think you could do it with:

    return (someString ?? string.Empty).Trim();
  • Some Jerk 2012-08-09 10:22
    Loren Pechtel:
    default_ex:
    That first function is horrendously over complicated for what it says it does.

    notNullString = ReturnEmptyStringIfNullElseValue(someString);

    notNullString = someString ?? string.Empty;

    Now it might just be because I actually know the language, but I find the second version much more readable.


    This does *NOT* produce the same results.

    I think you could do it with:

    return (someString ?? string.Empty).Trim();


    return string.Format("{0}", someString).Trim();
  • AnonymousCoder 2012-08-09 10:38
    I'm a programmer, not a philosopher


    If you are a programmer, you are a philosopher too, even if you don't realize that.
    Granted, those grandiloquent words sound like mouthful, but so is "deterministic finite state automaton", or "binary space partitioning trees", or even "object-oriented programming", although the latter term may appear cryptic only to outsiders.

    Just by the fact that you are reading this article, and engaging in arguments over coding practices - that in itself is philosophy.
  • Craig 2012-08-09 11:10
    Wow, you really are one of those arrogant pricks, aren't you?

    There's nothing wrong with VB.NET. Personally, I prefer C# and that's what I do for my job. But ultimately either language is syntactic sugar over the .NET Framework. As long as you're not writing your VB.NET like it's VB6 then I really don't see a problem with an individual or company settling on it as their language of choice.
  • Some Jerk 2012-08-09 11:23
    Craig:
    Wow, you really are one of those arrogant pricks, aren't you?

    There's nothing wrong with VB.NET. Personally, I prefer C# and that's what I do for my job. But ultimately either language is syntactic sugar over the .NET Framework. As long as you're not writing your VB.NET like it's VB6 then I really don't see a problem with an individual or company settling on it as their language of choice.


    Glad I am not the only one who sees it that way. Perhaps next year we will see people suggesting that the real WTF is that the coder was wearing blue when they wrote the code.

    I think arrogant might not be the most precise term however. How does ignorant and E-Biggot work for you?
  • Craig's friend 2012-08-09 11:31
    So true... I saw some kids complaining about why no generic and why using arraylist etc without knowing they were looking at .NET 1.0 or 1.1 as they never seen one before.

    These kids tend to create super cool linq code that loops and loops and loops and loops and wondering why their newly reengineered fancy code takes 30 minutes to produce output whilst that old clumpsy code took just few seconds to do the same job..

    TRWTF is really these arrogant kids with shallow knowledge not willing to understand why certain things are done in certin ways. Sure, string to string looks real stupid, but guys, it may be written by someone who is maybe less intelligent than you are.

    Also not only we use to write isnullorempty,but also isnullorwhitespace ourselves with exactly the same name not so long ago. Now some kids will say why you would do this and do that.. They just assume you are stupid before even ask you why.

    I really enjoy reading here and also find it mostly funny but this one just remind me of few kids with full of egos.
  • no laughing matter 2012-08-09 12:02
    AnonymousCoder:

    If you are a programmer, you are a philosopher too, even if you don't realize that.
    Granted, those grandiloquent words sound like mouthful, but so is "deterministic finite state automaton", or "binary space partitioning trees", or even "object-oriented programming", although the latter term may appear cryptic only to outsiders.

    I am wondering why your list does not include the grandiloquent Monad from functional programming.
  • no laughing matter 2012-08-09 12:16
    Craig's friend:
    So true... I saw some kids complaining about why no generic and why using arraylist etc without knowing they were looking at .NET 1.0 or 1.1 as they never seen one before.
    So false! As already explained by nisl, he was using TryParse, so he was using at least .NET 2.0.

    In other words: The post you are referring to is not "So true", it is only proof of even more ignorance!
    Craig's friend:
    TRWTF is really these arrogant kids with shallow knowledge not willing to understand why certain things are done in certin ways. Sure, string to string looks real stupid, but guys, it may be written by someone who is maybe less intelligent than you are.
    String to string is just a sure sign that the programmer was just to dumb to program at all.
  • shadowman 2012-08-09 15:15
    no laughing matter:
    To all of you defending this code: Learn to program proper!

    This codebase is a huge W-T-clusterFuck.

    1.) Violation of separation-of-concerns / single-responsibility-principle. Implementing too many functionality in each method.
    2.) Misleading method names: "ReturnEmptyStringIfNullElseValue" does not return the value, it returns the trimmed value.
    3.) Violation of Don't-Repeat-Yourself all over the place. Why the animosity against temporary / local variables? And that replace-code is repeated all ovparsinger again instead of put into a separate method.
    4.) What's the point of first as Int and if that fails, parsing as Decimal? Why not parse it as decimal from the beginning?
    5.) Other WTfs already pointed out: Calling ToString() on a string, inefficient coding: using Substring instead of an indexer to retrieve a single Char from a String.
    6.) What's the idea of accepting input data and convert it into a number even if it is not a number? One might accept the idea that a money input may be in the form "$123.45", but this code will also accept ",7$56$,18.$9". This is worse than PHP!



    Thank you, yes. It's not so much that the functions exist, it's that they're full of bugs!

    While we're at it, isNumeric fails on floating point strings, etc.
  • Stefan 2012-08-09 15:49
    I would not call the isNumeric code "one of the more... clever approaches". In Perl, my regular check that a string is a positive integer is

    if ($value =~ /^\d+$/) { ...


    The only other alternative is to load the
    Scalar::Util::looks_like_number
    function. Or you just convert to integer and live with the warning on standard error. Meh.
  • Paul Neumann 2012-08-09 16:07
    I like to include a .ToString() on a string reference at times, like when I'm writing a jump tree where every other branch has .ToString(), or when punching a bunch of other typed objects into a string collection. It generally makes the code quicker for the reader to digest.

    Also, in .NET, the compiler will see the implementation of String.ToString(), specifically "return this;" being the only statement in the body. It will be then inlined and in the next processing step, removed as redundant. There really is no efficiency concern. Even if there were, if you're concerned about a single jump, then NO vm based language is for you. Not Java, any .NET variant, Python, Perl, or PHP. From the looks, we only have one person here capable of C/C++ regurgitation. And a TRUE efficiency die hard would complain of the inefficiencies that C adds to the code. ASM or NOTHING!

    The real WTF here is that all of you "experienced" programmers here apparently cannot tell the difference between Java and C#. Even more disturbing is the number of contributers which do not realize this is not actually VB.NET
  • AnonymousCoder 2012-08-09 17:43
    I am wondering why your list does not include the grandiloquent Monad from functional programming.


    Because otherwise I'll end up sounding like the Architect I've no idea what the hell I'm saying...
    (watch at 56s)
  • John Hensley 2012-08-09 19:57
    Why does this only happen in software? Why, for example, is the auto industry not plagued with self-taught inventors who can't be bothered to understand the combustion cycle, so they produce car designs with coal-fired engines?
  • Some Jerk 2012-08-09 20:10
    John Hensley:
    Why does this only happen in software? Why, for example, is the auto industry not plagued with self-taught inventors who can't be bothered to understand the combustion cycle, so they produce car designs with coal-fired engines?


    it isn't the industry that fails to comply with the standard... it is your imagination that fails to comply with the concept. Think about it... how many recalls happen each decade by some auto manufacturer that made a defective seatbealt... or the power stearing pump was not rated for specific weather conditions? it is the same thing in every industry. 95% of people are there for the paycheck. 4% are there because they love their jobs... and want to be the best at it... and what is between... well... who knows?
  • AnonymousCoder 2012-08-09 22:36
    I've got a class with 10,000 (that's right, TEN THOUSANDS) lines, and growing.
    Wait till I show you what's in there ! It's a horror story !

    I just can't wait....and unless you posted it last week, it probably won't happen in my lifetime...


    Sarcasm aside - Oh I wish ! I wish to let it out, to burst into a rant over the code that's being written at my company - but there's one thing holding me. That's the Non Disclosure Agreement. And a few of the clauses in my contract, which explicitly prohibit me from bad mouthing the company or discrediting it.

    One day - I'll do it.

    The code is just so bad, it has to be exposed. It's a classic. Has everything - string arithmetic; procedural design in an OOP language; God class; lots of static classes with static methods and (lo and behold) public static fields; error handling by hiding - yes, it's the most blatant feature - exceptions are just swallowed (granted - not everyone); unchecked, unaccounted for global variables (you may think, hey - it's C#; don't matter, make singleton variables and mark them static); event handlers driven design, as substitute for polymorphism (of course, if you only have one class, you need handlers); dead code; commented blocks of junk which lay there for no reason; SQL database "layer" where you have to plug in parameters by index, longest sequence attaining 33 params (how the HELL could possibly a human keep track of that ?!)

    -- A freaking jungle layed out with mines. God, I love to hate it...
  • default_ex 2012-08-10 00:15
    Craig's friend:
    TRWTF is really these arrogant kids with shallow knowledge not willing to understand why certain things are done in certin ways. Sure, string to string looks real stupid, but guys, it may be written by someone who is maybe less intelligent than you are.


    I sort of agree with you on this point. Having worked with a wide variety of people I've grown to be more understanding, but there is a limit.

    The most important thing to consider with a programmer is that they'll be solving logic and math every time they go to work on a piece of code. Anyone that's put in the effort to learn the language well enough to write clumsy code is likely willing to learn more advanced concepts that'll turn them from a poor coder to a good coder.

    The one point in your post that's most important is the why. All too often we see things posted on code websites with little or no explanation on why it works or how it works. That's the most important thing to know, otherwise we just breed more copy-paste coders.

    However if someone is truly not intelligent enough to write decent code after a being given a fair chance to do so. Then their in the wrong field and will only endanger other people if their allowed to continue on as programmers. We have no way of knowing just how important our programs will be, for all we know the stuff could wind up being a core tool in a financial empire. We're in a position to do so much damage if our work screws up, that makes it our number one priority to ensure we remove as many fail clauses as possible.
  • Cbuttius 2012-08-10 05:15
    John Hensley:
    Why does this only happen in software? Why, for example, is the auto industry not plagued with self-taught inventors who can't be bothered to understand the combustion cycle, so they produce car designs with coal-fired engines?


    Maybe because in all other industries they go through some formal qualification with a recognised professional body, in your case engineering.

    With software there is no real formal qualification and people are usually hired because they have the right buzzwords on their CV/resume, where longevity in a firm is seen as a plus (albeit they may have got set in their incorrect ways seeing only one way of doing something) often stuck in a system that has moved on. So even if this wasn't written a long time ago here, the person may have brought this in from the way they did this in their previous company.
  • Cbuttius 2012-08-10 05:55
    1. Generic code is code that is not attached to any particular business logic and is commonly used all over your code.

    Having to put it into a class is a WTF'ery of the language because classes are not extendable. In C++ you would make these free functions and probably put them in a namespace. You can then write more functions as you need them and put them into the same namespace but in a different file. True that if they all build into one common shared object library you need to rebuild that library for those who want to use the new functions but it is still adding rather than editing. (If your build makefile uses a wildcard you don't need to modify that either). Whatever, having them in one file is a WTF of the language.

    This is because they insisted that it had to be "pure OO" and thus everything attached to an object. Purism over practicality.

    2. Having a function both strip whitespace and also convert null to empty string is not a WTF. The implementation used might be although I can't see it here. The name might be better and for commonly-used library code, finding good names for things is more essential. But then even some of the best known systems are known for poor naming choices.

    Probably far too late to change the names now, my guess is that they are already all over the code.

    3. Some of the others might be good contenders for using a regex and could possibly even be done as one-liners using them, but regexes look ugly in business code and don't belong there. I would rather see something like StringConversions.GetPrice( input_string ) in my business code than some horrible regex.
  • RayvenUK 2012-08-10 06:41
    Bob:
    I agree with Mr. Time and Space here. Code monkeys, as a breed, are far too eager to start shooting down everybody else's thinking. I believe it's because a lot of us have insecurities about our own abilities and by shooting first all the time it deflects attention from our own weaknesses and makes us feel better about ourselves. It's the one part of this field that really irks me. It's in other fields, too, but it seems to be rampant around programming in general.


    I object to being called a Code Monke..... oooh, a digital banana, yum.
  • no laughing matter 2012-08-10 07:32
    Cbuttius:
    1. Generic code is code that is not attached to any particular business logic and is commonly used all over your code.

    Having to put it into a class is a WTF'ery of the language because classes are not extendable.
    Well, that is not true for all OO-languages. E.g. Ruby and Smalltalk allow to extend existing classes. Not claiming that this really is a good idea: When multiple programmers work on the same codebase, there definitely is a risk of collisions.

    Cbuttius:

    In C++ you would make these free functions and probably put them in a namespace.
    Well, in a true OO language "everything is an object" and in a class-based OO-language an object is an instance of a class.

    So in such a true OO-language a namespace is an object, too, and there is no difference between putting the function in a namespace vs. adding a method to a class.

    Cbuttius:

    You can then write more functions as you need them and put them into the same namespace but in a different file.
    The rule that a class must be defined completely in one file is specific to Java, other OO-languages are more permissive and a real Smalltalk is image-based, not file-based.

    Cbuttius:

    This is because they insisted that it had to be "pure OO" and thus everything attached to an object. Purism over practicality.
    If your "they" means the inventors of the Java language then i won't object, but this claim of impracticality is not true for all OO-languages.

    Cbuttius:

    2. Having a function both strip whitespace and also convert null to empty string is not a WTF.
    There's nothing wrong if it is a composition of two other functions, one for stripping whitespace and one for converting null to empty string.

    This allows for all of these features to be used separately when needed. And this is exactly what's wrong with this code: Too much features lumped together in a single method, and when some of the features are needed again, they are "re-used" by Copy-and-Paste-programming.

    Cbuttius:

    Probably far too late to change the names now, my guess is that they are already all over the code.
    That's exactly what's refactoring is for, and refactoring works like a charm in Java and C# (it's much harder but still more-or-less works in dynamically-typed languages).

    But even when refactoring is not available: rename the function, and add a function with the old name to call your new function and mark the function with the old name as deprecated.

    If something is ill-named and you have to keep it for compatibility-reasons at least show a warning (e.g. by marking it as deprecated).
  • Some Jerk 2012-08-10 08:16
    Cbuttius:
    1. Generic code is code that is not attached to any particular business logic and is commonly used all over your code.

    Having to put it into a class is a WTF'ery of the language because classes are not extendable. In C++ you would make these free functions and probably put them in a namespace. You can then write more functions as you need them and put them into the same namespace but in a different file. True that if they all build into one common shared object library you need to rebuild that library for those who want to use the new functions but it is still adding rather than editing. (If your build makefile uses a wildcard you don't need to modify that either). Whatever, having them in one file is a WTF of the language.

    This is because they insisted that it had to be "pure OO" and thus everything attached to an object. Purism over practicality.

    2. Having a function both strip whitespace and also convert null to empty string is not a WTF. The implementation used might be although I can't see it here. The name might be better and for commonly-used library code, finding good names for things is more essential. But then even some of the best known systems are known for poor naming choices.

    Probably far too late to change the names now, my guess is that they are already all over the code.

    3. Some of the others might be good contenders for using a regex and could possibly even be done as one-liners using them, but regexes look ugly in business code and don't belong there. I would rather see something like StringConversions.GetPrice( input_string ) in my business code than some horrible regex.


    Getting to the obvious point here... c++ is c++ and .NET is .NET. If every language conducted things the same way, then there would be only 1 development environment.

    Yes... template functions are definately handy... but for those of us who don't use c++ every day, generic classes and methods are more consistent with our own daily workflow.

    Regex DOES belong in business code... for validation purposes most especially. I disagree with using it for data type conversions, but that is possibly more preference than anything.
  • Craig's friend's friend 2012-08-10 19:46
    no laughing matter:
    So false! As already explained by nisl, he was using TryParse, so he was using at least .NET 2.0.

    FAIL FAIL FAIL. Just because you read others codes with VS2015, it doesn't mean the original programmer actually written the code with .NET 2.0.

    Jon Haugsand:
    Bad coding, yes, but hardly a WTF.


  • Nagash 2012-08-10 20:13
    Sir, me wrote Parse, then come along Nagash's friend changed it to TryParse. Nagash's friend was proud of himself saving an exception on error resume next. Tmr it ain't laughing matter when you look at it from VS2020 the whole thing WTF!?!
    Me happy to receive support call my customer always happy
  • Neil 2012-08-13 10:50
    Nagesh:
    This ain't being necesary as Java having no null check on parse of Integar from String for performing reason.
    String str = "13";
    
    int n = -1;
    try {
    n = Integer.parseInt();
    catch (NumberFormatException ex) {}
    catch (NullPointerException ex) {}
    return n >= 0;


    This is meking Nagesh mother cry.
    Don't show her this then:
    int n = -1;
    
    try {
    n = Integer.parseInt(str);
    } finally {
    return n;
    }
  • Late_in_the_game 2012-08-16 23:27
    public static bool isNumeric(string value)
    {
    bool isNum = true;
    for (int i = 0; i < value.Length; i++)
    {
    if (!"1234567890".Contains(value.Substring(i, 1)))
    {
    isNum = false;
    }
    }
    return isNum;
    }

    Somebody might have already picked this up, but this method will only return false if the LAST char in value is not a digit.
    I can understand doing it this way instead of, say, trying to parse it and handling the exception, because throwing and catching an exception is relative expensive.

    2c
  • JM 2012-08-23 08:24
    I might excuse your post if you lack complete knowledge of C# in specific...and 'good programming patterns' in general.

    This post was one of the best WTFs recently.

    Anyone that doesn't think so should think long and hard as to why they don't get it.
  • JM 2012-08-23 08:25
    Above post was in regards to:

    Infinite Time and Space:
    There is no WTF here. These functions give you flexibility to handle cases that apply to your situation that the built-ins may not have. Putting them in one class supports easy refactoring. Also, this is a common and reasonable solution when the best available programmer is someone unfamiliar with all of the built in functions of a language. We get paid to get a good enough job done as efficiently as possible. Writing the world's greatest code is often contrary to that. The side effect is that experienced programmers often have to go in and clean up someone else's mess to add new features that the original planners could not have possibly foreseen. It is what we are paid to do. Deal with it or pick another career.


    Reply didn't inject any quote.
  • nelson_no_nose 2012-10-02 21:26
    AnonymousCoder:
    I've got a class with 10,000 (that's right, TEN THOUSANDS) lines, and growing.
    Wait till I show you what's in there ! It's a horror story !

    I just can't wait....and unless you posted it last week, it probably won't happen in my lifetime...


    Sarcasm aside - Oh I wish ! I wish to let it out, to burst into a rant over the code that's being written at my company - but there's one thing holding me. That's the Non Disclosure Agreement. And a few of the clauses in my contract, which explicitly prohibit me from bad mouthing the company or discrediting it.

    One day - I'll do it.

    The code is just so bad, it has to be exposed. It's a classic. Has everything - string arithmetic; procedural design in an OOP language; God class; lots of static classes with static methods and (lo and behold) public static fields; error handling by hiding - yes, it's the most blatant feature - exceptions are just swallowed (granted - not everyone); unchecked, unaccounted for global variables (you may think, hey - it's C#; don't matter, make singleton variables and mark them static); event handlers driven design, as substitute for polymorphism (of course, if you only have one class, you need handlers); dead code; commented blocks of junk which lay there for no reason; SQL database "layer" where you have to plug in parameters by index, longest sequence attaining 33 params (how the HELL could possibly a human keep track of that ?!)

    -- A freaking jungle layed out with mines. God, I love to hate it...


    This sounds so similar to a couple of the places I've worked. I've seen my share of God classes of tens of thousands of lines and megabytes in size which wouldn't be so bad if they at least weren't so messy with inconsistency as far as the eye can see. One was even called "Functions". Commented out code everywhere and renamed files that are no longer used. Worst still, swaths of obsolete code that is still executed but to no effect other than generating heat. Layers of indirection so deep that a call trace has more steps than the Great Pyramid of Giza would if it were made of Lego bricks. Function names and inline langdoc that has nothing to do with what the function does. So much copy and pasted repeat code that someone coding it by scratch could make something with way less than half as many lines. Somehow managing to write something in 500 lines with no redundant code that could be rewritten in 50 lines while being more secure, featured, accurate, stable and efficient. Rosetta comments everywhere such as (bookshelf->addBook(book);//add book to bookshelf). It goes on and on.

    What I find amazing is how pervasive these problems are. Whenever I think I have seen the worst of it, something else comes along. For a while I always wanted to expose it, but I've come to see so much of it that I just don't see the point of it.
  • TigerShark 2012-11-18 16:36
    Grzes:

    To all of you defending this code: Learn to program proper!

    This codebase is a huge W-T-clusterFuck.

    (...)


    I'm a programmer, not a philosopher, so I won't argue with such grandiloquent phrases as separation-of-concerns and single-responsibility-principle. I believe you are right (for most points), maybe in the Java world there is an emphasis on doing things in accordance to some specific doctrines and if it actually works is a secondary issue.

    However, I don't agree with point 5. I strongly deem that using both words "Java" and "efficiency" in one sentence is a stylistic error, because these words are simply incompatible.

    If you care about efficiency, don't use Java.
    If you use Java, don't aim for efficiency, because this is something you already lost choosing Java.
    Other than not being a philosopher you are neither a very good programmer if you are convinced that your obscene last two sentences are the Truth Revealed from God to humanity.
    Writing code in java and in other higher level languages more often increases the efficiency since the programmer is free to concentrate on the real problem that he has to solve rather than in the language intricacies.
    It is enough to take a look to the jruby performance and to compare it to the ruby reference implementation written in c++.
    In most cases jruby is much faster than ruby.
    So we can infer that java is always more efficient than c++?
    Of course not, but for sure we can say that your Absolute Truth that so gently you revealed to us, poor mere subhuman programmers, is just a bunch of crap.

    BTW I don't like java, I prefer much more c#.