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


.



Relevant Pages

  • Fomatted read from a csv file (FORTRAN 77)
    ... I have a matrix pop(tbstat, age, sex, expose, tentry) which I would ...
    (comp.lang.fortran)
  • Re: fields or properties
    ... > Consider a class Person with a public int property of Age and a public ... > validates input, ... I think it implies more that the author of the code ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: SubComponent to appear in main components properties?
    ... I am not sure this is direct equivalent to Delphi's SetSubComponent, but, as ... far as I remember, if you expose a sub-component through a public property, ... > click on + and see MySubObject's properties of (Height, Weight, age) ...
    (microsoft.public.dotnet.languages.csharp)
  • Protecting a babys ears...
    ... I have my first child due in 8 weeks time, and I'm keen to expose them to ... drumming from an early age. ... Has anyone seen ear defenders that are suitable ...
    (rec.music.makers.percussion)
  • Re: The new JJProdigy?
    ... Since we are sure he is of age, I wonder what else we could question ... Maybe we could expose to the poker world he is really a ... female or something real "interesting" like that. ...
    (rec.gambling.poker)

Loading