Public property or variable ?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Stefan De Schepper

    Public property or variable ?

    Should I use:

    Private m_Name As String

    Public Property Name() As String
    Get
    Return m_Name
    End Get
    Set(ByVal Value As String)
    m_Name = Value
    End Set
    End Property

    or just

    Public Name As String

    The last one just has to be faster, or am I wrong?

    Stefan


  • Herfried K. Wagner [MVP]

    #2
    Re: Public property or variable ?

    "Stefan De Schepper" <stefan.de.sche pper@skynet.be> schrieb:[color=blue]
    > Should I use:
    >
    > Private m_Name As String
    >
    > Public Property Name() As String
    > Get
    > Return m_Name
    > End Get
    > Set(ByVal Value As String)
    > m_Name = Value
    > End Set
    > End Property
    >
    > or just
    >
    > Public Name As String
    >
    > The last one just has to be faster, or am I wrong?[/color]

    If 'Name' is an attribute of the entity represented by the class, I strongly
    recommend to use a property instead of a public variable.

    --
    M S Herfried K. Wagner
    M V P <URL:http://dotnet.mvps.org/>
    V B <URL:http://classicvb.org/petition/>

    Comment

    • Scott M.

      #3
      Re: Public property or variable ?

      When you create a Property, you'll have a Set section to write validation
      code into. If you just use a Public field any string value passed to it
      must be accepted. Properties also help you create your class in a more
      object oriented way since the property acts as an abstraction layer to the
      internal data. In other words, you'll be creating more of a "black box" if
      you use the property.


      "Stefan De Schepper" <stefan.de.sche pper@skynet.be> wrote in message
      news:42dd6a01$0 $4281$ba620e4c@ news.skynet.be. ..[color=blue]
      > Should I use:
      >
      > Private m_Name As String
      >
      > Public Property Name() As String
      > Get
      > Return m_Name
      > End Get
      > Set(ByVal Value As String)
      > m_Name = Value
      > End Set
      > End Property
      >
      > or just
      >
      > Public Name As String
      >
      > The last one just has to be faster, or am I wrong?
      >
      > Stefan
      >
      >[/color]


      Comment

      • ThunderMusic

        #4
        Re: Public property or variable ?

        There is a major difference between the usefulness of properties and
        variables. There are what the others have said about it being more object
        oriented and it's true, but there are other reasons.

        Let's say, for some reason, you want the Name property to be readonly, you
        can't do it with the public variable, but you can with the property. Let's
        say you have some bug and you want to log every action in your application,
        but using a property you can add a line like Log.WriteLine(" SettingName: " &
        Value) and there you go. You can't do this neither with the public variable

        I hope you get the point and I hope it helps

        ThunderMusic

        "Stefan De Schepper" <stefan.de.sche pper@skynet.be> a écrit dans le message
        de news:42dd6a01$0 $4281$ba620e4c@ news.skynet.be. ..[color=blue]
        > Should I use:
        >
        > Private m_Name As String
        >
        > Public Property Name() As String
        > Get
        > Return m_Name
        > End Get
        > Set(ByVal Value As String)
        > m_Name = Value
        > End Set
        > End Property
        >
        > or just
        >
        > Public Name As String
        >
        > The last one just has to be faster, or am I wrong?
        >
        > Stefan
        >
        >[/color]


        Comment

        • Dennis

          #5
          RE: Public property or variable ?

          As you can see that from the responses, people on this newsgroup don't like
          fields but are stuck on properties. I find fields useful in certain
          situations and would suggest you use whatever is best for you. As for the
          speed, I wrote a test program to read and write to both a string field and a
          stirng property where the property was stored as a private variable. I did
          this for 10m cycles and found very little difference then upped it to 100m
          cycles and found that reading/writing to a field is pretty consistently 120
          seconds faster than reading/writing a property on my computer.
          --
          Dennis in Houston


          "Stefan De Schepper" wrote:
          [color=blue]
          > Should I use:
          >
          > Private m_Name As String
          >
          > Public Property Name() As String
          > Get
          > Return m_Name
          > End Get
          > Set(ByVal Value As String)
          > m_Name = Value
          > End Set
          > End Property
          >
          > or just
          >
          > Public Name As String
          >
          > The last one just has to be faster, or am I wrong?
          >
          > Stefan
          >
          >
          >[/color]

          Comment

          • Scott M.

            #6
            Re: Public property or variable ?

            As for your performance test, it's obvious that working with just the field
            will perform better. But, if you read the responses, you'll see why we are
            "stuck" on properties. They offer much more security and flexibility than
            fields and in all but the most demanding situations does the performance gap
            that you mention actually make a difference.


            "Dennis" <Dennis@discuss ions.microsoft. com> wrote in message
            news:FE96CCE2-0690-48E2-B843-699FAC835BD6@mi crosoft.com...[color=blue]
            > As you can see that from the responses, people on this newsgroup don't
            > like
            > fields but are stuck on properties. I find fields useful in certain
            > situations and would suggest you use whatever is best for you. As for
            > the
            > speed, I wrote a test program to read and write to both a string field and
            > a
            > stirng property where the property was stored as a private variable. I
            > did
            > this for 10m cycles and found very little difference then upped it to 100m
            > cycles and found that reading/writing to a field is pretty consistently
            > 120
            > seconds faster than reading/writing a property on my computer.
            > --
            > Dennis in Houston
            >
            >
            > "Stefan De Schepper" wrote:
            >[color=green]
            >> Should I use:
            >>
            >> Private m_Name As String
            >>
            >> Public Property Name() As String
            >> Get
            >> Return m_Name
            >> End Get
            >> Set(ByVal Value As String)
            >> m_Name = Value
            >> End Set
            >> End Property
            >>
            >> or just
            >>
            >> Public Name As String
            >>
            >> The last one just has to be faster, or am I wrong?
            >>
            >> Stefan
            >>
            >>
            >>[/color][/color]


            Comment

            • Jay B. Harlow [MVP - Outlook]

              #7
              Re: Public property or variable ?

              ThunderMusic,
              | Let's say, for some reason, you want the Name property to be readonly, you
              | can't do it with the public variable, but you can with the property.
              You can make public & private fields (variables) readonly, by adorning them
              with the Readonly keyword. Such as:

              Public Readonly Name As String

              When you use Readonly on a field you can only set the field in the
              constructor.

              Public Sub New(ByVal name As String)
              Me.Name = name
              End Sub

              I use readonly fields in my classes when the value of said field is
              immutable for the lifetime of that instance of the object. This ensures that
              I or one of my predecessors know that the field itself is not meant to
              change...

              NOTE: Readonly properties with read/write fields are useful for "State"
              properties such as SqlConnection.S tate where the property reports the
              "state" of the object, while other methods (Open, Close) modify that
              "state".

              | but using a property you can add a line like Log.WriteLine(" SettingName: "
              &
              | Value) and there you go. You can't do this neither with the public
              variable
              Agreed...

              Hope this helps
              Jay


              "ThunderMus ic" <NOdanylat@symp atico.caSPAMATA LL> wrote in message
              news:%23ElDwxKj FHA.2920@TK2MSF TNGP14.phx.gbl. ..
              | There is a major difference between the usefulness of properties and
              | variables. There are what the others have said about it being more object
              | oriented and it's true, but there are other reasons.
              |
              | Let's say, for some reason, you want the Name property to be readonly, you
              | can't do it with the public variable, but you can with the property. Let's
              | say you have some bug and you want to log every action in your
              application,
              | but using a property you can add a line like Log.WriteLine(" SettingName: "
              &
              | Value) and there you go. You can't do this neither with the public
              variable
              |
              | I hope you get the point and I hope it helps
              |
              | ThunderMusic
              |
              | "Stefan De Schepper" <stefan.de.sche pper@skynet.be> a écrit dans le
              message
              | de news:42dd6a01$0 $4281$ba620e4c@ news.skynet.be. ..
              | > Should I use:
              | >
              | > Private m_Name As String
              | >
              | > Public Property Name() As String
              | > Get
              | > Return m_Name
              | > End Get
              | > Set(ByVal Value As String)
              | > m_Name = Value
              | > End Set
              | > End Property
              | >
              | > or just
              | >
              | > Public Name As String
              | >
              | > The last one just has to be faster, or am I wrong?
              | >
              | > Stefan
              | >
              | >
              |
              |


              Comment

              • Jay B. Harlow [MVP - Outlook]

                #8
                Re: Public property or variable ?

                Dennis,
                | I did
                | this for 10m cycles and found very little difference then upped it to 100m
                | cycles and found that reading/writing to a field is pretty consistently
                120
                | seconds faster than reading/writing a property on my computer.

                I would expect your results to be closer to zero, as there is a good chance
                the JIT will inline the property Getter & Setter.





                Did you test the Debug or Release build of your app?

                Did you test from a command prompt or from Visual Studio?

                If you tested the Debug build from Visual Studio, then the JIT will not
                attempt to optimize the code. However if you tested the Release build from
                the command line then the JIT will attempt to "fully" optimize the code.

                Your numbers suggests you tested a Debug build, possible under Visual
                Studio!

                Try the following from a command prompt for both Debug & Release builds:

                Declare Function QueryPerformanc eCounter Lib "Kernel32" (ByRef X As
                Long) As Short
                Declare Function QueryPerformanc eFrequency Lib "Kernel32" (ByRef X As
                Long) As Short

                Private Class Person

                Public m_name As String

                Public Sub New(ByVal name As String)
                m_name = name
                End Sub

                Public Property Name() As String
                Get
                Return m_name
                End Get
                Set(ByVal value As String)
                m_name = value
                End Set
                End Property
                End Class

                Public Shared Sub Main()
                Const MaxCount As Integer = 1000000
                Const format As String = "{1}: {0}"

                Dim aPerson As New Person("Jay")

                For outerCount As Integer = 1 To 5
                Dim start, finish, frequency As Long
                QueryPerformanc eFrequency(freq uency)

                QueryPerformanc eCounter(start)
                For innerCount As Integer = 1 To MaxCount
                aPerson.Name = "Fred"
                Next
                QueryPerformanc eCounter(finish )
                Console.WriteLi ne(format, TimeSpan.FromSe conds((finish - start)
                / frequency), "Property")

                QueryPerformanc eCounter(start)
                For innerCount As Integer = 1 To MaxCount
                aPerson.m_name = "Fred"
                Next
                QueryPerformanc eCounter(finish )
                Console.WriteLi ne(format, TimeSpan.FromSe conds((finish - start)
                / frequency), "Field")
                Next

                End Sub

                For Debug builds you should see Property much larger then Field. For Release
                builds you should see both numbers nearly the same.

                Hope this helps
                Jay




                "Dennis" <Dennis@discuss ions.microsoft. com> wrote in message
                news:FE96CCE2-0690-48E2-B843-699FAC835BD6@mi crosoft.com...
                | As you can see that from the responses, people on this newsgroup don't
                like
                | fields but are stuck on properties. I find fields useful in certain
                | situations and would suggest you use whatever is best for you. As for
                the
                | speed, I wrote a test program to read and write to both a string field and
                a
                | stirng property where the property was stored as a private variable. I
                did
                | this for 10m cycles and found very little difference then upped it to 100m
                | cycles and found that reading/writing to a field is pretty consistently
                120
                | seconds faster than reading/writing a property on my computer.
                | --
                | Dennis in Houston
                |
                |
                | "Stefan De Schepper" wrote:
                |
                | > Should I use:
                | >
                | > Private m_Name As String
                | >
                | > Public Property Name() As String
                | > Get
                | > Return m_Name
                | > End Get
                | > Set(ByVal Value As String)
                | > m_Name = Value
                | > End Set
                | > End Property
                | >
                | > or just
                | >
                | > Public Name As String
                | >
                | > The last one just has to be faster, or am I wrong?
                | >
                | > Stefan
                | >
                | >
                | >


                Comment

                • Jay B. Harlow [MVP - Outlook]

                  #9
                  Re: Public property or variable ?

                  Stefan,
                  In addition to the other comments.

                  | The last one just has to be faster, or am I wrong?
                  Your wrong! The JIT compiler has the option to inline the property Get & Set
                  routines (actually any short method). Which means the Property will execute
                  exactly the same as a Field! See my response to Dennis on details & a
                  demonstration.



                  I would be more concerned about what is "correct". The property suggests
                  better encapsulation, remember Encapsulation is one of the major tenants of
                  OO.

                  Properties also play nicer with System.Componen tModel,
                  System.Windows. Forms.PropertyG rid and COM interop.

                  I would not code a field or property based on perceived runtime performance.

                  Remember the 80/20 rule. That is 80% of the execution time of your program
                  is spent in 20% of your code. I will optimize (worry about performance,
                  memory consumption) the 20% once that 20% has been identified & proven to be
                  a performance problem via profiling (CLR Profiler is one profiling tool).

                  For info on the 80/20 rule & optimizing only the 20% see Martin Fowler's
                  article "Yet Another Optimization Article" at




                  Here are some thoughts on not using properties:




                  Hope this helps
                  Jay


                  "Stefan De Schepper" <stefan.de.sche pper@skynet.be> wrote in message
                  news:42dd6a01$0 $4281$ba620e4c@ news.skynet.be. ..
                  | Should I use:
                  |
                  | Private m_Name As String
                  |
                  | Public Property Name() As String
                  | Get
                  | Return m_Name
                  | End Get
                  | Set(ByVal Value As String)
                  | m_Name = Value
                  | End Set
                  | End Property
                  |
                  | or just
                  |
                  | Public Name As String
                  |
                  | The last one just has to be faster, or am I wrong?
                  |
                  | Stefan
                  |
                  |


                  Comment

                  • Dennis

                    #10
                    Re: Public property or variable ?

                    You are correct in that I tested it in debug mode. As for using Properties
                    vs Fields, I fully understand the consequences of using one over the other so
                    I use what works for me in a particulair situation. I'm not a purist and I
                    know there are several ways to skin a cat! If I have a class that contains
                    something like a boolean value and it's independent of whatever else is in
                    the class, I see no reason to not just use a field.

                    --
                    Dennis in Houston


                    "Jay B. Harlow [MVP - Outlook]" wrote:
                    [color=blue]
                    > Dennis,
                    > | I did
                    > | this for 10m cycles and found very little difference then upped it to 100m
                    > | cycles and found that reading/writing to a field is pretty consistently
                    > 120
                    > | seconds faster than reading/writing a property on my computer.
                    >
                    > I would expect your results to be closer to zero, as there is a good chance
                    > the JIT will inline the property Getter & Setter.
                    >
                    > http://msdn.microsoft.com/library/de...anagedapps.asp
                    >
                    >
                    >
                    > Did you test the Debug or Release build of your app?
                    >
                    > Did you test from a command prompt or from Visual Studio?
                    >
                    > If you tested the Debug build from Visual Studio, then the JIT will not
                    > attempt to optimize the code. However if you tested the Release build from
                    > the command line then the JIT will attempt to "fully" optimize the code.
                    >
                    > Your numbers suggests you tested a Debug build, possible under Visual
                    > Studio!
                    >
                    > Try the following from a command prompt for both Debug & Release builds:
                    >
                    > Declare Function QueryPerformanc eCounter Lib "Kernel32" (ByRef X As
                    > Long) As Short
                    > Declare Function QueryPerformanc eFrequency Lib "Kernel32" (ByRef X As
                    > Long) As Short
                    >
                    > Private Class Person
                    >
                    > Public m_name As String
                    >
                    > Public Sub New(ByVal name As String)
                    > m_name = name
                    > End Sub
                    >
                    > Public Property Name() As String
                    > Get
                    > Return m_name
                    > End Get
                    > Set(ByVal value As String)
                    > m_name = value
                    > End Set
                    > End Property
                    > End Class
                    >
                    > Public Shared Sub Main()
                    > Const MaxCount As Integer = 1000000
                    > Const format As String = "{1}: {0}"
                    >
                    > Dim aPerson As New Person("Jay")
                    >
                    > For outerCount As Integer = 1 To 5
                    > Dim start, finish, frequency As Long
                    > QueryPerformanc eFrequency(freq uency)
                    >
                    > QueryPerformanc eCounter(start)
                    > For innerCount As Integer = 1 To MaxCount
                    > aPerson.Name = "Fred"
                    > Next
                    > QueryPerformanc eCounter(finish )
                    > Console.WriteLi ne(format, TimeSpan.FromSe conds((finish - start)
                    > / frequency), "Property")
                    >
                    > QueryPerformanc eCounter(start)
                    > For innerCount As Integer = 1 To MaxCount
                    > aPerson.m_name = "Fred"
                    > Next
                    > QueryPerformanc eCounter(finish )
                    > Console.WriteLi ne(format, TimeSpan.FromSe conds((finish - start)
                    > / frequency), "Field")
                    > Next
                    >
                    > End Sub
                    >
                    > For Debug builds you should see Property much larger then Field. For Release
                    > builds you should see both numbers nearly the same.
                    >
                    > Hope this helps
                    > Jay
                    >
                    >
                    >
                    >
                    > "Dennis" <Dennis@discuss ions.microsoft. com> wrote in message
                    > news:FE96CCE2-0690-48E2-B843-699FAC835BD6@mi crosoft.com...
                    > | As you can see that from the responses, people on this newsgroup don't
                    > like
                    > | fields but are stuck on properties. I find fields useful in certain
                    > | situations and would suggest you use whatever is best for you. As for
                    > the
                    > | speed, I wrote a test program to read and write to both a string field and
                    > a
                    > | stirng property where the property was stored as a private variable. I
                    > did
                    > | this for 10m cycles and found very little difference then upped it to 100m
                    > | cycles and found that reading/writing to a field is pretty consistently
                    > 120
                    > | seconds faster than reading/writing a property on my computer.
                    > | --
                    > | Dennis in Houston
                    > |
                    > |
                    > | "Stefan De Schepper" wrote:
                    > |
                    > | > Should I use:
                    > | >
                    > | > Private m_Name As String
                    > | >
                    > | > Public Property Name() As String
                    > | > Get
                    > | > Return m_Name
                    > | > End Get
                    > | > Set(ByVal Value As String)
                    > | > m_Name = Value
                    > | > End Set
                    > | > End Property
                    > | >
                    > | > or just
                    > | >
                    > | > Public Name As String
                    > | >
                    > | > The last one just has to be faster, or am I wrong?
                    > | >
                    > | > Stefan
                    > | >
                    > | >
                    > | >
                    >
                    >
                    >[/color]

                    Comment

                    Working...