Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. Other Discussions
  3. The Weird and The Wonderful
  4. IsNullOrEmpty

IsNullOrEmpty

Scheduled Pinned Locked Moved The Weird and The Wonderful
csharphtml
16 Posts 5 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A AspDotNetDev

    For shame! String is a class and all class instances get their references passed around (so there is no large copy when using ByVal). When you do ByRef, you actually pass a reference to that reference, allowing the source variable (used by the caller) to be assigned something different. Take this for example:

    Public Class Form1

    Private small As String = "a"
    Private large As String = "This was a really long string I shortened so I could paste it here easily..."
    Private Const MAX As Integer = 9999999
    Private startTime As DateTime
    Private endTime As DateTime
    Private smallDuration As Integer
    Private largeDuration As Integer
    Dim sb As System.Text.StringBuilder
    
    Private Sub Button1\_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    
        sb = New System.Text.StringBuilder()
        GC.Collect()
        GC.WaitForPendingFinalizers()
        startTime = DateTime.Now
        For i As Integer = 0 To MAX
            sb.Append(FirstChar(large))
        Next
        endTime = DateTime.Now
        largeDuration = CInt(endTime.Subtract(startTime).TotalMilliseconds)
    
    
        sb = New System.Text.StringBuilder()
        GC.Collect()
        GC.WaitForPendingFinalizers()
        startTime = DateTime.Now
        For i As Integer = 0 To MAX
            sb.Append(FirstChar(small))
        Next
        endTime = DateTime.Now
        smallDuration = CInt(endTime.Subtract(startTime).TotalMilliseconds)
    
    
        MessageBox.Show(String.Format("Small: {0}, Large: {1}", smallDuration.ToString(), largeDuration.ToString()))
    
    End Sub
    
    ' TODO: Try ByRef and ByVal, and compare them.
    Private Function FirstChar(ByRef str As String) As String
        Return str.Substring(0, 1)
    End Function
    

    End Class

    The timings in that example will always be very similar, whether you use a large string, a small string, ByRef, or ByVal. Using ByRef when you don't actually intend to treat that variable as an output from the function would be a coding horror! But don't stop there. There are plenty more horrors in the IsNullOrEmpty function. :)

    [WikiLeaks Cablegate Cables]

    OriginalGriffO Offline
    OriginalGriffO Offline
    OriginalGriff
    wrote on last edited by
    #4

    :-O You are right, I can only plead stupidity and not bothering to think before I commented!

    Real men don't use instructions. They are only the manufacturers opinion on how to put the thing together.

    "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
    "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

    1 Reply Last reply
    0
    • A AspDotNetDev

      For shame! String is a class and all class instances get their references passed around (so there is no large copy when using ByVal). When you do ByRef, you actually pass a reference to that reference, allowing the source variable (used by the caller) to be assigned something different. Take this for example:

      Public Class Form1

      Private small As String = "a"
      Private large As String = "This was a really long string I shortened so I could paste it here easily..."
      Private Const MAX As Integer = 9999999
      Private startTime As DateTime
      Private endTime As DateTime
      Private smallDuration As Integer
      Private largeDuration As Integer
      Dim sb As System.Text.StringBuilder
      
      Private Sub Button1\_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
      
          sb = New System.Text.StringBuilder()
          GC.Collect()
          GC.WaitForPendingFinalizers()
          startTime = DateTime.Now
          For i As Integer = 0 To MAX
              sb.Append(FirstChar(large))
          Next
          endTime = DateTime.Now
          largeDuration = CInt(endTime.Subtract(startTime).TotalMilliseconds)
      
      
          sb = New System.Text.StringBuilder()
          GC.Collect()
          GC.WaitForPendingFinalizers()
          startTime = DateTime.Now
          For i As Integer = 0 To MAX
              sb.Append(FirstChar(small))
          Next
          endTime = DateTime.Now
          smallDuration = CInt(endTime.Subtract(startTime).TotalMilliseconds)
      
      
          MessageBox.Show(String.Format("Small: {0}, Large: {1}", smallDuration.ToString(), largeDuration.ToString()))
      
      End Sub
      
      ' TODO: Try ByRef and ByVal, and compare them.
      Private Function FirstChar(ByRef str As String) As String
          Return str.Substring(0, 1)
      End Function
      

      End Class

      The timings in that example will always be very similar, whether you use a large string, a small string, ByRef, or ByVal. Using ByRef when you don't actually intend to treat that variable as an output from the function would be a coding horror! But don't stop there. There are plenty more horrors in the IsNullOrEmpty function. :)

      [WikiLeaks Cablegate Cables]

      F Offline
      F Offline
      fjdiewornncalwe
      wrote on last edited by
      #5

      I fail to see the great horror in your code... If you are posting in the Hall of Shame with a code snippet, should there not be at least one subtle horror in there? We are coming here to be amused, not educated... (Nicely explained, by the way. I actually ran into a few senior developers in my time who did not understand this concept)

      I wasn't, now I am, then I won't be anymore.

      P 1 Reply Last reply
      0
      • A AspDotNetDev

        A classic VB.Net mistake (I think somebody actually posted a variant recently), with a few extra goodies (copied verbatim from a class, StringAndText, a coworker wrote recently):

        ''' <summary>
        ''' Check if a string is null or empty
        ''' </summary>
        ''' <param name="str"></param>
        ''' <returns></returns>
        Public Shared Function IsNullOrEmpty(ByVal str As String) As Boolean

        If (str Is Nothing) OrElse (str = String.Empty) Then
            Return (True)
        End If
        
        Return (False)
        

        End Function

        Have at it. :-D

        [WikiLeaks Cablegate Cables]

        _ Offline
        _ Offline
        _Erik_
        wrote on last edited by
        #6

        Let's imagine that string.IsNullOrEmpty does not exist. Let's imagine that extension methods do not exist either. Let's imagine that a method like this might be useful. With all of these premises, I still think that someone should invent a computer which slapped anyone who wrote an "If" statement just to return the result of the condition evaluated by that "If". I have seen it countless times, and I still don't understand how they do not notice it.

        F 1 Reply Last reply
        0
        • _ _Erik_

          Let's imagine that string.IsNullOrEmpty does not exist. Let's imagine that extension methods do not exist either. Let's imagine that a method like this might be useful. With all of these premises, I still think that someone should invent a computer which slapped anyone who wrote an "If" statement just to return the result of the condition evaluated by that "If". I have seen it countless times, and I still don't understand how they do not notice it.

          F Offline
          F Offline
          fjdiewornncalwe
          wrote on last edited by
          #7

          If string.IsNullOrEmpty did not exist, I would create it in my source because it is a heavily used utility function, even if the the method only returns the results of an "if" evaluation. My reasoning for this is that the usage of stringVariable.IsNullOrEmpty() is very clear as to what is being evaluated while if( stringVariable == null || stringVariable.Length == 0 ) is not as clear. From a sustainability standpoint I would definitely create it. As a note, I always add this utility to all solutions that do not have the support natively.

          I wasn't, now I am, then I won't be anymore.

          _ 1 Reply Last reply
          0
          • F fjdiewornncalwe

            If string.IsNullOrEmpty did not exist, I would create it in my source because it is a heavily used utility function, even if the the method only returns the results of an "if" evaluation. My reasoning for this is that the usage of stringVariable.IsNullOrEmpty() is very clear as to what is being evaluated while if( stringVariable == null || stringVariable.Length == 0 ) is not as clear. From a sustainability standpoint I would definitely create it. As a note, I always add this utility to all solutions that do not have the support natively.

            I wasn't, now I am, then I won't be anymore.

            _ Offline
            _ Offline
            _Erik_
            wrote on last edited by
            #8

            Yes, sure, but what I meant was more about the implementation itself:

            public static bool IsNullOrEmpty(string str)
            {
            return str == null || str == "";
            }

            No need of an "if" statement since we are actually returning the result of the condition itself. This is what I meant.

            F P 2 Replies Last reply
            0
            • _ _Erik_

              Yes, sure, but what I meant was more about the implementation itself:

              public static bool IsNullOrEmpty(string str)
              {
              return str == null || str == "";
              }

              No need of an "if" statement since we are actually returning the result of the condition itself. This is what I meant.

              F Offline
              F Offline
              fjdiewornncalwe
              wrote on last edited by
              #9

              But do you want to write the entire "if" statement in hundreds of places in a large solution, or one that can be issued a test-case for coverage and validation that will then be validated from intellisense. Any equality statement is dangerous in the old "str = null" vs "str == null" world and thus should be encapsulated into a testable case.

              I wasn't, now I am, then I won't be anymore.

              A 1 Reply Last reply
              0
              • F fjdiewornncalwe

                But do you want to write the entire "if" statement in hundreds of places in a large solution, or one that can be issued a test-case for coverage and validation that will then be validated from intellisense. Any equality statement is dangerous in the old "str = null" vs "str == null" world and thus should be encapsulated into a testable case.

                I wasn't, now I am, then I won't be anymore.

                A Offline
                A Offline
                AspDotNetDev
                wrote on last edited by
                #10

                Marcus Kramer wrote:

                But do you want to write the entire "if" statement in hundreds of places in a large solution, or one that can be issued a test-case for coverage and validation that will then be validated from intellisense. Any equality statement is dangerous in the old "str = null" vs "str == null" world and thus should be encapsulated into a testable case.

                Uh, what? Are you saying that the if statement should be encapsulated in a method rather than sprinkling the if statement over several places in the code? Erik never said otherwise. He just said that rather than using an if statement, a single return statement can be used (yes, inside a method).

                [WikiLeaks Cablegate Cables]

                F 1 Reply Last reply
                0
                • A AspDotNetDev

                  Marcus Kramer wrote:

                  But do you want to write the entire "if" statement in hundreds of places in a large solution, or one that can be issued a test-case for coverage and validation that will then be validated from intellisense. Any equality statement is dangerous in the old "str = null" vs "str == null" world and thus should be encapsulated into a testable case.

                  Uh, what? Are you saying that the if statement should be encapsulated in a method rather than sprinkling the if statement over several places in the code? Erik never said otherwise. He just said that rather than using an if statement, a single return statement can be used (yes, inside a method).

                  [WikiLeaks Cablegate Cables]

                  F Offline
                  F Offline
                  fjdiewornncalwe
                  wrote on last edited by
                  #11

                  I stand corrected. I misread that last post from Erik.... :doh:

                  I wasn't, now I am, then I won't be anymore.

                  1 Reply Last reply
                  0
                  • F fjdiewornncalwe

                    I fail to see the great horror in your code... If you are posting in the Hall of Shame with a code snippet, should there not be at least one subtle horror in there? We are coming here to be amused, not educated... (Nicely explained, by the way. I actually ran into a few senior developers in my time who did not understand this concept)

                    I wasn't, now I am, then I won't be anymore.

                    P Offline
                    P Offline
                    PIEBALDconsult
                    wrote on last edited by
                    #12

                    Indeed, I'm in a VB shop now and it seems that someone thinks reference types always have be passed byref. :sigh:

                    F 1 Reply Last reply
                    0
                    • _ _Erik_

                      Yes, sure, but what I meant was more about the implementation itself:

                      public static bool IsNullOrEmpty(string str)
                      {
                      return str == null || str == "";
                      }

                      No need of an "if" statement since we are actually returning the result of the condition itself. This is what I meant.

                      P Offline
                      P Offline
                      PIEBALDconsult
                      wrote on last edited by
                      #13

                      Yes, but... make a generic one that takes any IList as well. (Oh how I wish String implemented IList. :sigh: ) (And don't compare to an empty string[^].)

                      _ 1 Reply Last reply
                      0
                      • P PIEBALDconsult

                        Indeed, I'm in a VB shop now and it seems that someone thinks reference types always have be passed byref. :sigh:

                        F Offline
                        F Offline
                        fjdiewornncalwe
                        wrote on last edited by
                        #14

                        Ain't that the truth... Ironically, I have a couple QA's who I'm mentoring in C# for web automation testing that have a better grasp... They have never taken any courses... (They also write better code, but I'll pretend that is because of me)

                        I wasn't, now I am, then I won't be anymore.

                        1 Reply Last reply
                        0
                        • P PIEBALDconsult

                          Yes, but... make a generic one that takes any IList as well. (Oh how I wish String implemented IList. :sigh: ) (And don't compare to an empty string[^].)

                          _ Offline
                          _ Offline
                          _Erik_
                          wrote on last edited by
                          #15

                          I can't see the problem...

                          return lst == null || lst.Count == 0;

                          Becouse if a class implements IList it must also implement ICollection.

                          P 1 Reply Last reply
                          0
                          • _ _Erik_

                            I can't see the problem...

                            return lst == null || lst.Count == 0;

                            Becouse if a class implements IList it must also implement ICollection.

                            P Offline
                            P Offline
                            PIEBALDconsult
                            wrote on last edited by
                            #16

                            Yes, but String isn't an IList -- but not to worry, I wrote... I wrote my own String class today. :cool:

                            1 Reply Last reply
                            0
                            Reply
                            • Reply as topic
                            Log in to reply
                            • Oldest to Newest
                            • Newest to Oldest
                            • Most Votes


                            • Login

                            • Don't have an account? Register

                            • Login or register to search.
                            • First post
                              Last post
                            0
                            • Categories
                            • Recent
                            • Tags
                            • Popular
                            • World
                            • Users
                            • Groups