Why all these get/set-methods instead of public variables?

I've started to use classes to structure up my programs and all tutorials i've read says that i should do like this:

class Spelare
{
   float positionX;

   public Spelare()
   {
      positionX = 100f;
   }
   public float PosX
   {
      get
      {
         
return positionX; 
      }
      
set
      {
         positionX =
value;
      }
   }
}

Are these get/set-functions realy necessary. Wouldn't it be better to declare the positionX as public and let all other classes acces it directly.
If i don't do anything else than return/give a value in the function it looks pretty useless in my eyes.
Or does it has something with memory leaks etc to do

//C


Answer this question

Why all these get/set-methods instead of public variables?

  • DecentViv

    I agree with Balir up to the point when he wishes to go further.

    Interfaces are clearly not needed for all classes.

    As to the books: their usefulness depends on whence one comes to the material. The 3 listed are in C++, C++, & Java, respectively, and are what I would consider 'advanced reading'.

    OTOH, that the question was 'why properties ' suggests to me that an 'easier' introduction might be warranted. For engineers, I would recommend 'C# Precisely'. for others, 'Core C# and .NET'.

    The hardest part of this programming biz is learning the .NET framework, which far exceeds the size of the C# language. To learn both, 'Framework Design Guidelines' might be a place to start. This last book offers advice in 4 flavors: Do, Consider Avoid, Don't. They lead off their section on Interfaces with this stmt: "In general, classes are the preferred construct for exposing abstractions." followed by a discussion of the inflexibility of Interfaces.

  • baolsen

    naah, not a jab, the penguin is a found item, and just ... 'cute'. Probably manufactured rather than captured.

  • Jim Svoboda

    Because none of us can foresee the future . . .Big Smile

    In Effective C#: Fifty Ways to Improve Your C# [Wagner addison-wesley,2005 ISBN 0321245660], the first and longest essay addressses the question.

    The last paragraph is -

    Whenever you expose data in your type's public or protected interfaces, use properties. Use an indexer for sequences or dictionaries. All data memembers should be private, without exception. You immediately get support for databinding, and you make it much easier to make any change to the implementations of the methods in the future. The extra typing to encapsulate any variable in a property amounts to one or two minutes a day. Finding that you need to use properties later to correctly express your designs will take hours. Spend a little time now, and save lots of time later.

    given VS2005's ability to refactor on the fly, it isnt even that much time.

    I will go further. . . all your properties - and events - should be first defined in interfaces.

    and still further. . . All your classes should implement one or more interfaces.

    Does it ever stop. . . All your methods/indexers that operate on objects should be passed interfaces and not classes in their prototypes.

    I suggest you get three books -

    Object Oriented Analysis and Design With Applications [booch]
    Design Patterns: Elements of Reusable Object-Oriented Software [gamma, et al]
    Refactoring: Improving the Design of Existing Code [fowler] 

    No programmer should be without these three.


  • DanL43

    After reading your comments and rereading my statements. . . I guess I would amend #1, as it is probably inaccurate as to what I do in practice. . .

    My interfaces are usually defined on the 'pass through.' Typically after I hack for a while then go back and abstract out to an Interface. And I guess in specific units that will be atomic I do have some non-interfaced elements.

    Typically, if I inherit from IDisposable or derive from Component, all properties/methods/events end up in an interface either initially or after refactoring.

    But you are right. . . I generally don't start with a specifying the interface. On the other hand, before I define a method/eventarg/property/delegate that uses a class, I stop and look at the class and usually end up deriving and/or using an interface for it instead.

    The reasons I recommend the books I did is because of the question 'why properties ' It is my belief that it is better to understand the concepts of OOP before delving into a particular implementation. I find that understanding inheritance, polymorphism, aggregation, etc. . . makes it easier when beginning development in an OO language.

    C# and .Net in general, make OO development a breeze - but they don't necessarily make for good OO. Does that make sense

    Its kind of like Databases. Access/SQL Server make Database development simple. But at the same time, they also make it simple to build bad database design. They are wonderful tools if you know what you are doing. . . if you don't - they are dangerous!

    Nothing beats a solid foundation in theory. 

  • sontek

     dsweb7870 wrote:
    How are you in using inheritance and polymorphism

    To be honest, this was the first time i ever heard the words :p
    But the post above described a pretty good understandable reason why to not use public variables :)

  • Ron Beck

    Well, I will give a very good reason why you make member variables private. If you don't this will enable the users of the class to get access to data that you may not want them to, be able to change the data to what they want at any time and perhaps bypass all security in the code.
    Having checks in the get/set code to prevent this is much smaller and neater than having checks in each method to make sure the user hasn't done anything stupid.
    The other reason is as stated before, classes are generally a black box, the user shouldn't need to know what goes on inside. But in order to do that you must make the interface consistant if you decide that you need to change something. So if you redefine member variables but you can still manage to support it via the get and set, then there is no reason to change the interface.
    These are what Microsoft class as breaking and non breaking changes. Changes to windows which mean you have to edit the sourcecode to get it to work are breaking changes, changes where you don't have to do anything are non breaking. In most cases people are happier if they don't need to edit their code because you decided that a certain interface is better.

  • Enishi69

    BTW. . . I love the penguin!

    is that a jab at linux

  • Trey Harrison

    to ease the setting of fields, consider a series of constructors with appropriate arguments to set those fields, like this

    MyClass( int a, int b, int c ){...}

    MyClass( int a, int b) : this (a,b,defaultc) {}

    MyClass( int a ) : this(a, defaultb, defaultc ) {}

    MyClass() : this(defaulta, defaultb, defaultc) {}



  • sterimick

    I agree.... Each time a new class is created you have to set the property for each class variable after initializing the constructor.  This makes adding the code very tedious, plus I do not understand the point of having them.

    How are you in using inheritance and polymorphism


  • Shekhar Gupta

    and on top of that, if you are using VS2005, declare your fields privately at the beginning then right click to refactor to properties.

    If you really think it is unecessary, then fine, don't do it. But I guarantee this. . .

    In six months something like this is going to happen. You will look at one of your public fields and you will say, 'Man, I wish I could keep track of when ThisValue changes!' (event handler in the set method)  or 'Man, I wish I could bind ThisValue to ThatTextBox!' (only properties are bindable) or 'Man, I wish I could easily prevent ThisValue from being an empty string!' (value checking and exception raising in the set method)



  • Why all these get/set-methods instead of public variables?