fields or properties

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

    fields or properties

    Hello,
    I don't know when to use fields and when to used properties. It looks to
    me that using properties is always better. But I guess fields must be
    better in some cases, otherwise they wouldn't exist!

    Thank you
    Julien
  • glenn

    #2
    Re: fields or properties

    Well, lets see. I think maybe you are confused about the difference between
    them as they are very different things. The easiest way to answer this
    would be with an example I guess.

    When you write a class you more times than not need variables to hold data
    in order for the class to operate correctly. These variables that are
    defined in the class are known as fields. They are really nothing more than
    variables defined in the class to hold data in order for the class to work
    its magic.

    However, there is a major problem with exposing these variables(field s) to
    the user of the class. Just because you are writing the class and
    understand how its suppose to work, doesn't mean the guy next year that
    creates an instance of your class will understand all the inner workings of
    it.

    So when you lay out your class and one of the fields named "CustPhone" needs
    to always be formatted like: 111-111-1111, you can't be sure the guy using
    your class or even you will remember that later on.

    In comes properties. Properties are really not variables at all, but are
    rather functions that handle writing and reading from your internal
    variables or fields. By using the Set and Get features of properties you
    are now able to control what gets written to and read from your internal
    fields, keeping the users of your classes from being able to enter corrupt
    data into the class that might cause failure later down the road.

    Hopefully that helps you understand the difference. Fields and Properties
    are always used together and should really be in most class designs, unless
    you have no real reason to provide a property to access a field. But the
    fields are always there no matter what as a property is useless if it has
    nothing to write to.

    Good luck and I hope I understood your question.

    glenn


    "julien" <julien@sobrier .net> wrote in message
    news:425d54c4$0 $1250$636a15ce@ news.free.fr...[color=blue]
    > Hello,
    > I don't know when to use fields and when to used properties. It looks to
    > me that using properties is always better. But I guess fields must be
    > better in some cases, otherwise they wouldn't exist!
    >
    > Thank you
    > Julien[/color]


    Comment

    • julien

      #3
      Re: fields or properties

      So, fields should be private only and properties public?

      Comment

      • Jon Skeet [C# MVP]

        #4
        Re: fields or properties

        julien <julien@sobrier .net> wrote:[color=blue]
        > So, fields should be private only and properties public?[/color]

        Yes - although properties don't have to be public, either. It can often
        be useful to have internal, protected or even private properties.

        --
        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

        • Bob Powell [MVP]

          #5
          Re: fields or properties

          Fields should be private or protected. In a good OO architecture there is no
          real reason for a feild to ever be public.

          Protected feilds are valid because they can be used by derived classes but
          your architecture should be designed with the pro's and cons of allowing
          derived classes access to base feilds.

          Making a field public breaks the rules of encapsulation because it allows
          external code to modify a value without the knowlege of the encapsulating
          class.

          --
          Bob Powell [MVP]
          Visual C#, System.Drawing

          Find great Windows Forms articles in Windows Forms Tips and Tricks


          Answer those GDI+ questions with the GDI+ FAQ


          All new articles provide code in C# and VB.NET.
          Subscribe to the RSS feeds provided and never miss a new article.





          "julien" <julien@sobrier .net> wrote in message
          news:425d5eea$0 $6791$626a14ce@ news.free.fr...[color=blue]
          > So, fields should be private only and properties public?[/color]


          Comment

          • glenn

            #6
            Re: fields or properties

            Hey Bob, I tried to check out your site that you have in your signature but
            its down. Is it down or do you have a bad link in your signature?

            Thanks,

            glenn

            "Bob Powell [MVP]" <bob@_spamkille r_bobpowell.net > wrote in message
            news:eJsi16GQFH A.3140@tk2msftn gp13.phx.gbl...[color=blue]
            > Fields should be private or protected. In a good OO architecture there is[/color]
            no[color=blue]
            > real reason for a feild to ever be public.
            >
            > Protected feilds are valid because they can be used by derived classes but
            > your architecture should be designed with the pro's and cons of allowing
            > derived classes access to base feilds.
            >
            > Making a field public breaks the rules of encapsulation because it allows
            > external code to modify a value without the knowlege of the encapsulating
            > class.
            >
            > --
            > Bob Powell [MVP]
            > Visual C#, System.Drawing
            >
            > Find great Windows Forms articles in Windows Forms Tips and Tricks
            > http://www.bobpowell.net/tipstricks.htm
            >
            > Answer those GDI+ questions with the GDI+ FAQ
            > http://www.bobpowell.net/faqmain.htm
            >
            > All new articles provide code in C# and VB.NET.
            > Subscribe to the RSS feeds provided and never miss a new article.
            >
            >
            >
            >
            >
            > "julien" <julien@sobrier .net> wrote in message
            > news:425d5eea$0 $6791$626a14ce@ news.free.fr...[color=green]
            > > So, fields should be private only and properties public?[/color]
            >
            >[/color]


            Comment

            • Michael S

              #7
              Re: fields or properties

              One of the most long-lived dogma in the OO-purists camp is to never expose
              fields as public.

              However, I think there can be benefits in having public fields.

              Consider a class Person with a public int property of Age and a public
              string field called Name.

              What the class Person tells you is that the Age property is somewhat
              managed, perhaps the property validates that an age isn't a negative number
              and so forth. The property protects you in some manner.

              But the class also tells you that the Name field is not handled at all. The
              Person class won't mind if you serialize an mp3-file to a hexstring and use
              that as a name, hence it is your responsebility to check that input is
              meaningful.

              By going by the idiom of sporting all fields private and have public getters
              and setters for all those fields, is extra work and bloats your code. But
              what I think is worse is having Name as a property, which implies that it
              validates input, while in fact it doesn't.

              However, in some situations, like building user controls in asp.net; you
              must sport all your fields as properties.

              Hope this helps
              - Michael S


              Comment

              • glenn

                #8
                Re: fields or properties

                Actually I fail to see your point. There seem to be a couple things you
                might be forgetting.

                1) Its impossible to know today what might come up next week or even next
                year that causes a design to change. Starting out with public fields allows
                decendents of a class to directly access those fields, even if later you
                decide that exposing the customer name field was a huge mistake. Having it
                use properties up front might take a little extra work on your part, but
                your class is much more adaptable to future needs.

                2) Your argument that exposing a field allows your class to be much more
                powerful seems rediculous. What it seems you are actually doing is making
                your class much less capable of changing with future needs that may arrise
                because trying to go back and change a public field to a private field might
                be an impossible task 2 years later.

                If you choose to have public fields in your class designs then that is your
                business and perhaps it works for you, however, telling someone that doesn't
                understand the ramifications of doing that, that you "Should" do it, seems a
                little rediculous. I think that exposing fields like that should be given
                extreme care and in the end, I just don't see the advantage. You saved
                yourself a very few keystrokes up front, but what have you potentially done
                to yourself and those using your components later on?

                Sorry if my wording sounds like I'm attacking you as I'm not. Just
                expressing my opinion...

                just my 2 cents,

                glenn


                "Michael S" <a@b.c> wrote in message
                news:OcDEmyOQFH A.4028@tk2msftn gp13.phx.gbl...[color=blue]
                > One of the most long-lived dogma in the OO-purists camp is to never expose
                > fields as public.
                >
                > However, I think there can be benefits in having public fields.
                >
                > Consider a class Person with a public int property of Age and a public
                > string field called Name.
                >
                > What the class Person tells you is that the Age property is somewhat
                > managed, perhaps the property validates that an age isn't a negative[/color]
                number[color=blue]
                > and so forth. The property protects you in some manner.
                >
                > But the class also tells you that the Name field is not handled at all.[/color]
                The[color=blue]
                > Person class won't mind if you serialize an mp3-file to a hexstring and[/color]
                use[color=blue]
                > that as a name, hence it is your responsebility to check that input is
                > meaningful.
                >
                > By going by the idiom of sporting all fields private and have public[/color]
                getters[color=blue]
                > and setters for all those fields, is extra work and bloats your code. But
                > what I think is worse is having Name as a property, which implies that it
                > validates input, while in fact it doesn't.
                >
                > However, in some situations, like building user controls in asp.net; you
                > must sport all your fields as properties.
                >
                > Hope this helps
                > - Michael S
                >
                >[/color]


                Comment

                • Jon Skeet [C# MVP]

                  #9
                  Re: fields or properties

                  Michael S <a@b.c> wrote:[color=blue]
                  > One of the most long-lived dogma in the OO-purists camp is to never expose
                  > fields as public.
                  >
                  > However, I think there can be benefits in having public fields.
                  >
                  > Consider a class Person with a public int property of Age and a public
                  > string field called Name.
                  >
                  > What the class Person tells you is that the Age property is somewhat
                  > managed, perhaps the property validates that an age isn't a negative number
                  > and so forth. The property protects you in some manner.
                  >
                  > But the class also tells you that the Name field is not handled at all. The
                  > Person class won't mind if you serialize an mp3-file to a hexstring and use
                  > that as a name, hence it is your responsebility to check that input is
                  > meaningful.
                  >
                  > By going by the idiom of sporting all fields private and have public getters
                  > and setters for all those fields, is extra work and bloats your code. But
                  > what I think is worse is having Name as a property, which implies that it
                  > validates input, while in fact it doesn't.[/color]

                  I don't think it's particularly implying that - you're just inferring
                  it incorrectly. I think it implies more that the author of the code
                  cares about OO purity and the *potential* for validation in a future
                  release (while maintaining backward compatibility of both source and
                  binary).

                  --
                  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

                  • Bruce Wood

                    #10
                    Re: fields or properties

                    glenn,

                    While I agree with you, and I never use public fields myself, do recall
                    that your advice applies only for programmers who are releasing DLLs to
                    the public, and so are bound by the contract that they create at the
                    outset.

                    If you release DLLs outside your organization (or work group), it _is_
                    difficult to change a public field to a public property, because it
                    requires that all client code be recompiled.

                    However, if you are doing in-house development and all code is under
                    control of your IS department, then it is _dead easy_ to change a
                    public field into a property later if the design requires it. All you
                    have to do is recompile all client code, which is a minor annoyance at
                    worst.

                    I'm not advocating using public fields... I don't, as a matter of O-O
                    purity, as Jon Skeet pointed out.. I just wanted to point out that for
                    some of us it's not as bad as you make it out to be. It really depends
                    upon what kind of development you're doing and who is going to be
                    calling your DLLs.

                    Comment

                    • Bruce Wood

                      #11
                      Re: fields or properties

                      glenn,

                      While I agree with you, and I never use public fields myself, do recall
                      that your advice applies only for programmers who are releasing DLLs to
                      the public, and so are bound by the contract that they create at the
                      outset.

                      If you release DLLs outside your organization (or work group), it _is_
                      difficult to change a public field to a public property, because it
                      requires that all client code be recompiled.

                      However, if you are doing in-house development and all code is under
                      control of your IS department, then it is _dead easy_ to change a
                      public field into a property later if the design requires it. All you
                      have to do is recompile all client code, which is a minor annoyance at
                      worst.

                      I'm not advocating using public fields... I don't, as a matter of O-O
                      purity, as Jon Skeet pointed out.. I just wanted to point out that for
                      some of us it's not as bad as you make it out to be. It really depends
                      upon what kind of development you're doing and who is going to be
                      calling your DLLs.

                      Comment

                      • glenn

                        #12
                        Re: fields or properties

                        Bruce, while I can see your point, its still incorrect for the following
                        reason:

                        Lets say I write a class and have a field in it that is public. I deploy
                        that class to only myself as in your example its not a big deal if I do
                        that.

                        I use this class for 2 years all the while writing directly to this field as
                        its my only method of doing so. My boss comes to me today and he informs
                        me that we have a serious problem. That fields contents are being written
                        to based on user input, and the users are seriously screwing up the data in
                        the field. We need to do some verification on the field before we write the
                        data into the class.

                        So, I now know more than I knew then, and I know that to do this, I need to
                        prevent anyone from writing to that field (Me in this case) and start
                        validating the input through a property. So I go and change the type to
                        private and provide the necessary property to Get and Set the fields value
                        along with my appropriate validation code and recompile all my apps that
                        used that class as this is not a big deal, right?

                        Wrong! The problem now is that I've since used that class a grand total of
                        122 times throughout 10 different modules, all writing to a field that is
                        now private and therefore doesn't exist. So now I have to go throughout all
                        this source code and update it before I can recompile and redistribute all
                        the necessary peices.

                        So, we can talk proper OO standards and processes, or we can just talk
                        facts. Having public fields in my opinion is just not very smart in the
                        long run. It may get the job done quickly today but what is to say it will
                        still work tomorrow. And when it does require another process what will it
                        take to fix it?

                        For me, I'd much rather have a series of get and sets for each field that
                        never get used than to take a chance of having a major headache one day when
                        someone asks me to do something I hadn't planned on.

                        Just my 2cents,

                        glenn


                        Comment

                        • Michael S

                          #13
                          Re: fields or properties


                          "glenn" <ghancock@softe ksoftware.com> wrote in message
                          news:u2MiLJPQFH A.3288@TK2MSFTN GP14.phx.gbl...[color=blue]
                          > Actually I fail to see your point. There seem to be a couple things you
                          > might be forgetting.[/color]

                          From what I have read below, I can see that you failed to see my point. But
                          I'll try to explain it to you.
                          As a systems architect, I am responsible for making sure that each project
                          I'm involved in; have a certain amount of quality; they vary in scale and
                          can easily be translated into how much our customers are willing to pay.

                          'Quality' for me, is a jagged array. There is performance issues, milestone
                          issues, deadline issues, readability and maintainability , and also a lot of
                          coffee involved. But in the end; - Quality == Economics.
                          [color=blue]
                          > 1) Its impossible to know today what might come up next week or even next
                          > year that causes a design to change. Starting out with public fields
                          > allows
                          > decendents of a class to directly access those fields, even if later you
                          > decide that exposing the customer name field was a huge mistake. Having
                          > it
                          > use properties up front might take a little extra work on your part, but
                          > your class is much more adaptable to future needs.[/color]

                          RUP might think so, while Agile-spawned methologies having the
                          YAGNI-principle. - You Ain't Gonna Need It!

                          How often do entities change? Do we code in Notepad or Visual Studio? How
                          much time does it take to refactor a sequence of objects? I know that ctrl-h
                          enables me to search and replace. VS2005 and especially Eclipse have
                          excellent support for turning a field into a property (get./set-method), and
                          a property into a method.

                          This is the real problem with the oldschool OO-purist camp. They still live
                          in a world of Notepad (edlin?) and Emacs. .NET is built on namespaces and
                          typed classes, not files and variant functions. Refactoring is a simple task
                          nowadays. Many principles in OO are just dogma.
                          [color=blue]
                          > 2) Your argument that exposing a field allows your class to be much more
                          > powerful seems rediculous. What it seems you are actually doing is making
                          > your class much less capable of changing with future needs that may arrise
                          > because trying to go back and change a public field to a private field
                          > might
                          > be an impossible task 2 years later.[/color]

                          Rediculous?

                          This is the classic Java-argument. They don't need Properties and Events
                          (while still having them in .jsp/struts in an awkward way *s*).

                          The Java argument: - Sure we don't need properties, we can settle for
                          getters and setters. We don't need events, we can have nested classes and
                          interfaces.

                          The great thing with (Anders Hjelsberg and...) the MPE-model, Methods,
                          Properties and Events, is that the destinction tells you something.

                          And I've heard the argument before. - But what if a property does work? But
                          if the method just return a value?

                          - Well, then you are a lousy coder and don't belong in my crew. The argument
                          is just not there. What if a programmer write the boolean method IsValid
                          that deletes all files with .mp3 as an extention on all your drives? That
                          dude is evil, incompetent and/or have a serious communication problems.

                          It's all about granularity. If you know how to use MPE and fields you know
                          what to expect. If you do it wrong you just have poor communication skills
                          as a coder.
                          [color=blue]
                          > If you choose to have public fields in your class designs then that is
                          > your
                          > business and perhaps it works for you, however, telling someone that
                          > doesn't
                          > understand the ramifications of doing that, that you "Should" do it, seems
                          > a
                          > little rediculous. I think that exposing fields like that should be given
                          > extreme care and in the end, I just don't see the advantage. You saved
                          > yourself a very few keystrokes up front, but what have you potentially
                          > done
                          > to yourself and those using your components later on?[/color]

                          Oh, I see your problem. The ctrl-shift-h and a find/replace takes seconds. A
                          ctrl-shift-b to rebuild also takes seconds. And by your reasoning; I should
                          have my coders do hours of coding and pageup/pagedown for the fear of
                          change?

                          Change is natural. There is nothing to fear. This is our job...

                          I do code in languages that sports properties. One of them is C#. Another is
                          Delphi. For obvious reasons netiher can handle a property as ref (var). And
                          that may be one argument why public fields are bad. If you sport a field and
                          it turns into a property it will no longer work with out and ref in C# and
                          therefor break code.

                          But there is a simple solution to that problem: - Treat fields as
                          properties.
                          As properties may or may not do work and may or may not do validation, we
                          already have the idiom of always making sure to pull the value from a
                          property once, use it locally, and set it after your done with it. The grand
                          old snapshot/transaction dilemma.

                          - Treat fields as properties.

                          Tada! Problem solved...
                          [color=blue]
                          > Sorry if my wording sounds like I'm attacking you as I'm not. Just
                          > expressing my opinion...[/color]

                          This is an interesting topic. Our opinions may vary, the arguments may be
                          flamable; but I do respect you while I attack you!

                          My argument is still:

                          If a class (Person) denotes a concept of description (Name) while the class
                          has no concept of what Name might contain, it is far better to keep it as a
                          public field than turning into a property that does nothing.

                          A Method implies Work.
                          A Property implies Knowledge
                          An Event implies Action.
                          A field is just a variable (with type).

                          I live by the above implicit rules.

                          And back to Economics. If you worked for me and spent (invoicing)-time on
                          making a field into a property that does nothing, you would get some serious
                          spanking an also have to de-bloat your code on you spare time. Your code
                          would simple not pass my eye-balling test...
                          [color=blue]
                          >
                          > just my 2 cents,[/color]

                          I see your 2 cents and raise you 5. And I will raise you on the flop, street
                          and river. I've got two aces.. =)
                          [color=blue]
                          > glenn[/color]

                          - Michael S


                          Comment

                          • Michael S

                            #14
                            Re: fields or properties


                            "Bruce Wood" <brucewood@cana da.com> wrote in message
                            news:1113504362 .417457.107250@ g14g2000cwa.goo glegroups.com.. .[color=blue]
                            > glenn,
                            >
                            > While I agree with you, and I never use public fields myself, do recall
                            > that your advice applies only for programmers who are releasing DLLs to
                            > the public, and so are bound by the contract that they create at the
                            > outset.
                            >
                            > If you release DLLs outside your organization (or work group), it _is_
                            > difficult to change a public field to a public property, because it
                            > requires that all client code be recompiled.
                            >
                            > However, if you are doing in-house development and all code is under
                            > control of your IS department, then it is _dead easy_ to change a
                            > public field into a property later if the design requires it. All you
                            > have to do is recompile all client code, which is a minor annoyance at
                            > worst.
                            >
                            > I'm not advocating using public fields... I don't, as a matter of O-O
                            > purity, as Jon Skeet pointed out.. I just wanted to point out that for
                            > some of us it's not as bad as you make it out to be. It really depends
                            > upon what kind of development you're doing and who is going to be
                            > calling your DLLs.
                            >[/color]

                            Bruce!

                            Thanks for coming to the rescue! Even if you don't agree with me totally.
                            But I just like your mindset and are hoping that you will comment on my
                            reply to glenn.

                            - Michael S


                            Comment

                            • Michael S

                              #15
                              Re: fields or properties


                              "Jon Skeet [C# MVP]" <skeet@pobox.co m> wrote in message
                              news:MPG.1cc8c6 c7ee83b1c298bfd 2@msnews.micros oft.com...
                              [color=blue]
                              > I don't think it's particularly implying that - you're just inferring
                              > it incorrectly. I think it implies more that the author of the code
                              > cares about OO purity and the *potential* for validation in a future
                              > release (while maintaining backward compatibility of both source and
                              > binary).[/color]

                              Inferring and Implying and perhaps Lying is just labels for the same
                              concept.
                              What I am trying to say is that granularity matters. See my reply to glenn.

                              There should be no confusion. The field Name and the property Age. What do
                              they communicate?

                              I think (and do expect) that anyone calling themself a 'coder', 'dev' or a
                              'programmer' have no problem with this.

                              The public getter for a private field is just old dogma. And of no use...

                              I vote for granularity!

                              With my sincere respect
                              - Michael S



                              Comment

                              Working...