setting private fields in a constructor

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Michael Roper

    setting private fields in a constructor

    If a class uses public properties to expose private fields, and has a
    constructor to initialize those fields, should the constructor set them
    directly or use the set accessors? Or does it matter?

    Michael Roper


  • Jasper Kent

    #2
    Re: setting private fields in a constructor

    I don't think there's a general answer to this one.

    If the set accessor simply sets the field and nothing more, then there's
    not much odds. One might worry that the set accessor is a bit slower,
    but I think that will be optimised away in most cases. However, even if
    the set accessor does nothing special, there is always the issue that it
    might do something in future.

    If the set accessor does do something special, then its a question of
    whether you want to do that special thing. As class desginer you know
    what needs to be done and you can make the decisions.

    For example, suppose you have a set accessor that ensures an int is in
    the range 0-10, and throws an exception if not. If you call it with a
    hard-coded 0 in the constructor, then you're wasting time going through
    the set accessor. However, if the restriction were to change, then 0
    might become invalid and you'd want to catch that.

    If the set accessor were to, say, count the number of times that the
    field was changed, then you certainly wouldn't want to increment that
    count from the constructor, because thats initialisation, not change.

    Another issue to consider is if the property is virtual. If so, then you
    probably should call the set accessor to pick up any derived
    functionality, but again it may depend on the context. Also, calling
    virtual methods from a constructor is always dubious - less so in C#
    than it was in C++, but still not great.

    Regards,

    Jasper Kent

    *** Sent via Developersdex http://www.developersdex.com ***
    Don't just participate in USENET...get rewarded for it!

    Comment

    • Michael Roper

      #3
      Re: setting private fields in a constructor

      Thanks for the thoughtful reply Jasper.

      Michael Roper


      Comment

      • Michael Mayer

        #4
        Re: setting private fields in a constructor

        Just to put in my two-cents. I almost always use the property getter /
        setter within my own classes - including the constructor. If I'm doing any
        sort of bounds checking / error checking then I surely want to make sure I
        continue to use that, inside or outside of my class. Purely cosmetic, but I
        generally think the code is easier to read - at least for me:

        public MyClass()
        {
        Width = 10;
        }

        vs.

        public MyClass()
        {
        _width = 10; // or
        this.width = 10;
        }

        Plus, I think it helps encapsulation even more. Say you move _width and
        _height into a _size or _rectangle structure, then you just change your
        properties and the rest of your code still works.

        There are, of course, some places where I don't use the property (for
        example, maybe I need to reset a field to null within my class, but I don't
        allow other classes to do that). But most of the time, I prefer to use the
        property.

        --
        Mike Mayer
        真人高清实拍女被破的视频,影音先锋熟女少妇,青青青国产最新视频在线观看,在线看人成呦呦视频影,亚洲永久网址在线观看,国产成人综合亚洲欧美,视频免费在线观看,国产精品欧美一区二区久久久

        mike@mag37.com


        "Jasper Kent" <jasper_kent@ho tmail.com> wrote in message
        news:eTFnBHqeDH A.1716@TK2MSFTN GP10.phx.gbl...[color=blue]
        > I don't think there's a general answer to this one.
        >
        > If the set accessor simply sets the field and nothing more, then there's
        > not much odds. One might worry that the set accessor is a bit slower,
        > but I think that will be optimised away in most cases. However, even if
        > the set accessor does nothing special, there is always the issue that it
        > might do something in future.
        >
        > If the set accessor does do something special, then its a question of
        > whether you want to do that special thing. As class desginer you know
        > what needs to be done and you can make the decisions.
        >
        > For example, suppose you have a set accessor that ensures an int is in
        > the range 0-10, and throws an exception if not. If you call it with a
        > hard-coded 0 in the constructor, then you're wasting time going through
        > the set accessor. However, if the restriction were to change, then 0
        > might become invalid and you'd want to catch that.
        >
        > If the set accessor were to, say, count the number of times that the
        > field was changed, then you certainly wouldn't want to increment that
        > count from the constructor, because thats initialisation, not change.
        >
        > Another issue to consider is if the property is virtual. If so, then you
        > probably should call the set accessor to pick up any derived
        > functionality, but again it may depend on the context. Also, calling
        > virtual methods from a constructor is always dubious - less so in C#
        > than it was in C++, but still not great.
        >
        > Regards,
        >
        > Jasper Kent
        >
        > *** Sent via Developersdex http://www.developersdex.com ***
        > Don't just participate in USENET...get rewarded for it![/color]


        Comment

        • Daniel O'Connell

          #5
          Re: setting private fields in a constructor

          The danger comes when Width is virtual because it may attempt to do things
          with objects that are not yet initalized.
          "Michael Mayer" <mike@mag37.com > wrote in message
          news:unKAG0veDH A.3896@tk2msftn gp13.phx.gbl...[color=blue]
          > Just to put in my two-cents. I almost always use the property getter /
          > setter within my own classes - including the constructor. If I'm doing[/color]
          any[color=blue]
          > sort of bounds checking / error checking then I surely want to make sure I
          > continue to use that, inside or outside of my class. Purely cosmetic, but[/color]
          I[color=blue]
          > generally think the code is easier to read - at least for me:
          >
          > public MyClass()
          > {
          > Width = 10;
          > }
          >
          > vs.
          >
          > public MyClass()
          > {
          > _width = 10; // or
          > this.width = 10;
          > }
          >
          > Plus, I think it helps encapsulation even more. Say you move _width and
          > _height into a _size or _rectangle structure, then you just change your
          > properties and the rest of your code still works.
          >
          > There are, of course, some places where I don't use the property (for
          > example, maybe I need to reset a field to null within my class, but I[/color]
          don't[color=blue]
          > allow other classes to do that). But most of the time, I prefer to use[/color]
          the[color=blue]
          > property.
          >
          > --
          > Mike Mayer
          > http://www.mag37.com/csharp/
          > mike@mag37.com
          >
          >
          > "Jasper Kent" <jasper_kent@ho tmail.com> wrote in message
          > news:eTFnBHqeDH A.1716@TK2MSFTN GP10.phx.gbl...[color=green]
          > > I don't think there's a general answer to this one.
          > >
          > > If the set accessor simply sets the field and nothing more, then there's
          > > not much odds. One might worry that the set accessor is a bit slower,
          > > but I think that will be optimised away in most cases. However, even if
          > > the set accessor does nothing special, there is always the issue that it
          > > might do something in future.
          > >
          > > If the set accessor does do something special, then its a question of
          > > whether you want to do that special thing. As class desginer you know
          > > what needs to be done and you can make the decisions.
          > >
          > > For example, suppose you have a set accessor that ensures an int is in
          > > the range 0-10, and throws an exception if not. If you call it with a
          > > hard-coded 0 in the constructor, then you're wasting time going through
          > > the set accessor. However, if the restriction were to change, then 0
          > > might become invalid and you'd want to catch that.
          > >
          > > If the set accessor were to, say, count the number of times that the
          > > field was changed, then you certainly wouldn't want to increment that
          > > count from the constructor, because thats initialisation, not change.
          > >
          > > Another issue to consider is if the property is virtual. If so, then you
          > > probably should call the set accessor to pick up any derived
          > > functionality, but again it may depend on the context. Also, calling
          > > virtual methods from a constructor is always dubious - less so in C#
          > > than it was in C++, but still not great.
          > >
          > > Regards,
          > >
          > > Jasper Kent
          > >
          > > *** Sent via Developersdex http://www.developersdex.com ***
          > > Don't just participate in USENET...get rewarded for it![/color]
          >
          >[/color]


          Comment

          • Michael Roper

            #6
            Re: setting private fields in a constructor

            Michael Mayer writes:[color=blue]
            > I almost always use the property getter/setter
            > within my own classes - including the constructor.[/color]

            I like this approach, and the encapsulation point you made later also
            appeals. However, I'm having trouble getting the behavior I'd like (or
            expect) from properties in a couple of regards.

            One, I seem unable to assign different access modifiers for the set and get
            of a property. For example, I might like to have a private setter
            (something I'd do on behalf of the class client in the constructor, say) and
            a public getter.

            Two, I can't stick the private field associated with a property in the
            property itself (thereby enforcing property-only access to the field even
            within the class, and enhancing encapsulation).

            I'm sure there's a good reason I can't do these things, but it seems like
            they'd be nice to have.

            Michael Roper


            Comment

            • Jon Skeet

              #7
              Re: setting private fields in a constructor

              Michael Roper <michaelr@encra ft.com> wrote:[color=blue]
              > Michael Mayer writes:[color=green]
              > > I almost always use the property getter/setter
              > > within my own classes - including the constructor.[/color]
              >
              > I like this approach, and the encapsulation point you made later also
              > appeals. However, I'm having trouble getting the behavior I'd like (or
              > expect) from properties in a couple of regards.
              >
              > One, I seem unable to assign different access modifiers for the set and get
              > of a property.[/color]

              Indeed. That's being fixed in the next version of C#.
              [color=blue]
              > For example, I might like to have a private setter
              > (something I'd do on behalf of the class client in the constructor, say) and
              > a public getter.[/color]

              Absolutely.
              [color=blue]
              > Two, I can't stick the private field associated with a property in the
              > property itself (thereby enforcing property-only access to the field even
              > within the class, and enhancing encapsulation).
              >
              > I'm sure there's a good reason I can't do these things, but it seems like
              > they'd be nice to have.[/color]

              I don't think there *is* a good reason, I'm afraid - I've put in the
              latter as a feature request, but I don't know whether or not it'll be
              heeded. For the benefit of serialization etc, it would probably be
              worth having an extra attribute which allowed methods to access
              property-scoped variables, but that (and some naming restrictions) are
              the only wrinkles I can see.

              --
              Jon Skeet - <skeet@pobox.co m>
              Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

              If replying to the group, please do not mail me too

              Comment

              • Michael Roper

                #8
                Re: setting private fields in a constructor

                Thanks for your response Jon. I find the traffic in this group rather
                overwhelming--I don't know how you do it!

                Jon Skeet writes:[color=blue][color=green]
                >> One, I seem unable to assign different access
                >> modifiers for the set and get of a property.[/color]
                >
                > Indeed. That's being fixed in the next version of C#.[/color]

                That'll help. Is there a definitive "next version of C#" doc/timeline to be
                had?

                Michael Roper


                Comment

                • Willy Denoyette [MVP]

                  #9
                  Re: setting private fields in a constructor


                  "Jon Skeet" <skeet@pobox.co m> wrote in message news:MPG.19d049 00c208ab599896b 2@news.microsof t.com...[color=blue]
                  > Michael Roper <michaelr@encra ft.com> wrote:[color=green]
                  > > Michael Mayer writes:[/color][/color]
                  [color=blue][color=green]
                  > > One, I seem unable to assign different access modifiers for the set and get
                  > > of a property.[/color]
                  >
                  > Indeed. That's being fixed in the next version of C#.[/color]

                  Jon, Are you sure about this? Any references?

                  Willy.




                  Comment

                  • Willy Denoyette [MVP]

                    #10
                    Re: setting private fields in a constructor



                    "Willy Denoyette [MVP]" <willy.denoyett e@pandora.be> wrote in message news:emBY2bDfDH A.3204@TK2MSFTN GP11.phx.gbl...[color=blue]
                    >
                    > "Jon Skeet" <skeet@pobox.co m> wrote in message news:MPG.19d049 00c208ab599896b 2@news.microsof t.com...[color=green]
                    > > Michael Roper <michaelr@encra ft.com> wrote:[color=darkred]
                    > > > Michael Mayer writes:[/color][/color]
                    >[color=green][color=darkred]
                    > > > One, I seem unable to assign different access modifiers for the set and get
                    > > > of a property.[/color]
                    > >
                    > > Indeed. That's being fixed in the next version of C#.[/color]
                    >
                    > Jon, Are you sure about this? Any references?
                    >
                    > Willy.
                    >
                    >
                    >
                    >[/color]
                    Jon, Did some research myself, and you were right, this feature is planned for the next release of C# and VB.NET.

                    Willy.


                    Comment

                    Working...