tags:

views:

427

answers:

7

Hi, my question is simple, is using the get set properties of C# considered good, better even than writing getter and setter methods? When you use these properties, don't you have to declare your class data members as public ? I ask this because my professor stated that data members should never be declared as public, as it is considered bad practice.

This....

class GetSetExample
{
    public int someInt { get; set; }
}

vs This...

class NonGetSetExample
{
    private int someInt;
}

Edit:

Thanks to all of you! All of your answers helped me out, and I appropriately up-voted your answers.

+4  A: 

In your first example C# automatically generates the private backing fields so technically the data member is not declared as public only the getter/setter.

Michael Gattuso
Technically, but it's quite a meaningless distinction.
Noon Silk
Not really. Properties can be used in other areas whereas methods or fields cannot. Auto-binding comes to mind.
Michael Gattuso
It is actually quite important in some situations. If you declare a public variable then you're stuck with it being a public variable unless you want to change the ABI to that assembly. With a { get; set; } public property, all public accesses are happening through accessor methods so you can change the accessor methods to have different functionality later on without forcing everyone to recompile their apps that reference your assembly.
Nate C-K
Yes ... You two have written accurate responses, but they don't address my comment. He was highlighting that the data member isn't public; My comment is: So what?
Noon Silk
Silky, Michael answered your 'so what' correctly. For more detail, the CLR compiles them differently under the hood, which impacts how you do reflection-based operations (like his databinding example).
Paul
A: 

It's quite reasonable, and your professor (without context) is wrong. But anyway, using "automatic properties", is fine, and you can do it whether they are public or private.

Though in my experience, whenever I use one, I almost inevitably end up needing to write some logic in there, and hence can't use the auto props.

Noon Silk
I would guess the context would be Java (or possibly C++), as Java does not have properties as C#.
FrustratedWithFormsDesigner
If you have complete control over the entire source and it's always compiled together then it really makes little difference whether you use properties or public variables (except in special situations). However, in situations where different people are writing different parts of the code, it becomes more important. Professional libraries do not expose public variables to outside code.
Nate C-K
Reading these responses I feel a bit like I'm in the twilight zone.
Noon Silk
@FrustratedWithFormsDesigner: The idiomatic construct in Java is to define methods `getMyField` and `setMyField` to get and set private backing field `myField`.
Jason
+10  A: 

This:

class GetSetExample
{
    public int someInt { get; set; }
}

is really the same as this:

class GetSetExample
{
    private int _someInt;
    public int someInt {
        get { return _someInt; }
        set { _someInt = value; }
    }
}

The get; set; syntax is just a convenient shorthand for this that you can use when the getter and setter don't do anything special.

Thus, you are not exposing a public member, you are defining a private member and providing get/set methods to access it.

Nate C-K
+4  A: 

Yes, members should normally never be declared public in good design for several reasons. Think about OOP where you inherit the class later. Kind of hard to override a field. :-) Also it prevents you from keeping your internals from being accessed directly.

The simplistic get; set; design was introduced in C# 2.0. It's basically the same as declaring everything with a private member backing it (decompile it out in tool like Reflector and see).

public int someInt{get;set;}

is directly equal to

private int m_someInt;
public int someInt{
  get { return m_someInt; }
  set { m_someInt = value; }
}

The great part about having the simplified getter/setter is that when you want to fill in the implementation with a little bit more guts later, you do not break ABI compatibility.

Don't worry about getter/setters slowing down your code through indirection. The JIT has a thing called inlineing makes using the getter/setter just as efficient as direct field access.

Zac Bowling
I agree. Considering a long live .NET library. To maintain it, you must be very careful before exposing something to the outside world, and most of the time you should expose a property, instead of a field.This is the safest way as in future versions, you can feel free to change the implementation of this property without hurting the calling assemblies.What will happen if you expose a field directly? That must be a endless nightmare as you can never change it from then on.
Lex Li
+1  A: 

In a "pure" object oriented approach, it is not considered OK to expose the state of your objects at all, and this appliese to properties as they are implemented in .NET and get_ set_ properteis of Java/EJB. The idea is that by exposing the state of your object, you are creating external dependencies to the internal data representation of your object. A pure object design reduces all interactions to messages with parameters.

Back to the real world: if you try to implement such a strict theoretical approach on the job, you will either be laughed out of the office or beaten to a pulp. Properties are immensely popular because they are a reasonable compromise between a pure object design and fully exposed private data.

Paul Keister
+5  A: 

Yes. Data members should be private and automatic properties allow it and give public access on right way.

But you should be careful. Understand the context is very important. In threaded application, update one property following an another related property can be harmful to consistency. In that case, a setter method updating the two private data members in a proper way makes more sense.

bigown
A: 

your professor was quite right.

Consider this trivial example of why "getters" should be avoided: There may be 1,000 calls to a getX() method in your program, and every one of those calls assumes that the return value is a particular type. The return value of getX() may be sotred in a local variable, for example, and the variable type must match the return-value type. If you need to change the way that the object is implemented in such a way that the type of X changes, you're in deep trouble. If X used to be an int, but now has to be a long, you'll now get 1,000 compile errors. If you fix the problem incorrectly by casting the return value to int, the code will compile cleanly but won't work. (The return value may be truncated.) You have to modify the code surrounding every one of those 1,000 calls to compensate for the change. I, at least, don't want to do that much work.

Holub On Patterns

just somebody