I don't like this… Is this cheating the language?

前端 未结 15 2657
一向
一向 2021-02-13 15:52

I have seen something like the following a couple times... and I hate it. Is this basically \'cheating\' the language? Or.. would you consider this to be \'ok\' because the IsNu

相关标签:
15条回答
  • 2021-02-13 16:12

    A bit off topic but if you rand the same example in vb.net like this

    dim someString as string
    someString = MagicFunction()
    if not string.IsNullOrEmpty(someString) and someString.Length > 3 then
        ' normal string, do whatever
    else
        ' do someting else
    end if
    

    this would go bang on a null (nothing) string but in VB.Net you code it as follows do do the same in C#

    dim someString as string
    someString = MagicFunction()
    if not string.IsNullOrEmpty(someString) andalso someString.Length > 3 then
        ' normal string, do whatever
    else
        ' do someting else
    end if
    

    adding the andalso make it behave the same way, also it reads better. as someone who does both vb and c' development the second vb one show that the login is slighty different and therefor easyer to explain to someone that there is a differeance etc.

    Drux

    0 讨论(0)
  • 2021-02-13 16:14

    If it were code in c that you compiled into assembly, not only is short-circuiting the right behavior, it's faster. In machine langauge the parts of the if statement are evaluated one after another. Not short-circuiting is slower.

    0 讨论(0)
  • 2021-02-13 16:16

    This is valid code, in my opinion (although declaring a variable and assigning it on the next line is pretty annoying), but you should probably realize that you can enter the else-block also in the condition where the length of the string is < 3.

    0 讨论(0)
  • 2021-02-13 16:22

    If you are asking if its ok to depend on the "short circuit" relational operators && and ||, then yes thats totally fine.

    0 讨论(0)
  • 2021-02-13 16:22

    That looks to me like a perfectly reasonable use of logical short-circuitting--if anything, it's cheating with the language. I've only recently come from VB6 which didn't ever short-circuit, and that really annoyed me.

    One problem to watch out for is that you might need to test for Null again in that else clause, since--as written--you're winding up there with both Null strings and length-less-than-three strings.

    0 讨论(0)
  • 2021-02-13 16:25

    I find it OK :) You're just making sure that you don't access a NULL variable. Actually, I always do such checking before doing any operation on my variable (also, when indexing collections and so) - it's safer, a best practice, that's all ..

    0 讨论(0)
提交回复
热议问题