35
jkuhl
5y

To all the programmers calling “ToString()” on variables that are already of type String....

Please stop.

Comments
  • 11
    Brogrammer: *not sure if string, better call toString*

    TheRestOfUs: (┛ಠ_ಠ)┛彡┻━┻
  • 21
    But my string isn't stringy enough, I need more string!
  • 5
    I feel like toString on strings should just be forbidden to be called by compilers and interpreters.
  • 2
    Although, in the case of JavaScript, lazy typing might prevent that from being a good practice.
  • 1
    @kescherRant
    That would break encapsulation in unintuitive ways :) more a style thing in this case.
  • 1
    @SortOfTested Oh well, maybe I shouldn't design languages.
  • 2
    @kescherRant
    Never know unless you try!
  • 0
    Perhaps there is a corner case where it returns a non-string. So it is a catch-all. Maybe it was easier than tracking down the corner case.
  • 5
    Kids : *calls toString() on objects*
    Men: *calls toString() on String*
    Legends: *Calls toString() on null*
    Ultra legends : calls (""+null).toString()
  • 2
    It’s as disgusting as

    if (true === booleanMethod())
  • 1
    "How about no?".ToString();
  • 6
    "fiber".ToString()

    >> Output:
  • 3
    @C0D4 i've got a fever. And the only thing that can fix it, is more string!
  • 0
  • 1
    Just making sure.
  • 0
    I call ToString() 3 times on each string, just to make sure it's a string. It's good practice.
  • 0
    IDE's flag that normally for me
  • 2
    @AlmondSauce It's not like that computer has anything better to do anyway...
  • 0
    Well if you could assign values to an element of a string we probably wouldn't have this shit.
  • 0
    "Yo dawg".toString()
  • 1
    (str: string) => String(„ToString“).toString()
  • 0
    What language? Does it have strict typing? Does it guarantee input not being null when strict typed? Or does it only cast zero characters for overloading purposes? Because e.g. C#:

    > string s = null;

    > IPAddress i = null;

    > Console.WriteLine(object.Equals(s, i)); // prints "True"

    > Console.WriteLine(object.ReferenceEquals(s, i)); // prints "True"

    I understand the rant but it's not always obvious you have a string in the first place even if your IDE and static analyser claim you do. Also, `toString()` might be doing something different than what you think, e.g. presetting an overload without casting type so... all and all, it's safer to call that extra casting. Not saying I do it, I hate future-proofing. Saying I understand why experienced coders sometimes choose to do it.
Add Comment