tags:

views:

252

answers:

4

Possible Duplicate:
C# - When to use properties instead of functions

I am trying to understand when and why to use "getters" and "setters"

would someone please provide some guidance.

What is the difference between the following constructs - please look in terms of accessor methods only.

//EXAMPLE 1: simple accessor method 
private static bool _isInitialEditMapPageLoad;
public static bool isInitialEditMapPageLoad
{
    get {return _isInitialEditMapPageLoad;}
    set {_isInitialEditMapPageLoad = value;}
}

//EXAMPLE 2: accessor method with a conditional test
private static bool _isInitialEditMapPageLoad;
public static bool isInitialEditMapPageLoad
{
    get 
    {
        if (currentSession[isAuthorizedUseder] == null)
            return false;
        else
            return _isInitialEditMapPageLoad;    
    }
    set {isInitialEditMapPageLoad = value;} 
}


//EXAMPLE 3: just a get accessor method - is this the same as EXAMPLE 4?
private static bool _isInitialEditMapPageLoad = false;
public static bool isInitialEditMapPageLoad
{
    get {return _isInitialEditMapPageLoad;}
}


//EXAMPLE 4: simple method
private static bool _isInitialEditMapPageLoad = false; 
public static bool isInitialEditMapPageLoad
{
  return _isInitialEditMapPageLoad;     
}
+7  A: 

Your getters/setters should be your public interface to your class.

As a rule of thumb, all of your members should be private except for what you want people to have access to outside of your class and you never want your private variables to be directly accessible outside if your class

Here's a simple example. say you had a class that you needed an age variable for. In this case, you could perform validation right there in the setter without your external classes needing to know that the value is validated.

class Person {
  int age = 0;

  public int Age {
    get { return age; }
    set { 
      //do validation
      if (valid) {
        age = value;
      }
      //Error conditions if you want them.
    }
  } 

  //More getters/setters
}
Robert Greiner
+3  A: 

The reasoning behind Getters/Setters is to protect the class from being broken when a user alters a field in an invalid way, and they allow you to change the implementation of your class while leaving the publicly exposed properties unchanged.

Unless you need some kind of validation or lazy-loaded properties then you can usually just use auto properties.

public string Name { get; set; }
Struan
+1  A: 

1: This is a simple property, and can be used in much the same way as a public field. If you have a reason to expose both get and set operations to other users (that is, other classes) and you don't need anything fancy, this is it. This can also be written with "auto-properties",

public static bool isInitialEditMapPageLoad {get;set;} // behaves just like example 1

auto props are much faster to write and in my opinion are much more readable than the full declaration (if I see a full declaration with a backing field, I expect to find some complexity).

2: This shows one of the reasons for properties: using some logic to return a value rather than always returning a value directly. Somebody can set this value as they would a public field whenever they want. They can get the value whenever they want, as well, with the caveat that false means either this isn't the initial load OR the user isn't authorized -- that is, some (simple) logic is done before returning a value.

3: This behaves as a public field ONLY for reading -- somebody can retrieve the value, but not set it. This is in essence a value that is read only to outside code (not to be confused with the readonly keyword)

4: Resulted in a compilation error for me. Assuming that is supposed to be a method declaration, manually defining a getter like one would do in Java, then it is similar to example 3. I believe there are other issues that make this not quite the same, like if you want to turn this into a dependency property, etc. Unfortunately my knowledge in that area comes up short.

==========

As a general rule, user properties to limit access to your class data. As a principle, anything that you can keep from allowing other code to touch, should be kept that way. As a practical matter, you will want to be able to set values on classes to change how they display, modify the data represented, et cetera. Use properties to maintain maximum control of this interaction.

If other classes will need to view something in your class, you'll need to expose a getter, but not a setter. This isn't possible with fields, unless you use the Java method of writing a custom getter method. They also allow you to perform calculations or validations before returning or setting data. For example, if you have some integer value that should be within some range (a range which can change depending on the state of your object, even), in your setter you can check to make sure this condition is met before actually updating your value.

Try to avoid the trap of just setting everything as an autoprop -- this is no different than making everything a public field. Keep everything as private as possible. No getters unless necessary, no setters unless necessary, and setters should perform any small logic necessary to verify input before accepting it, if appropriate. That said, avoid the other trap: putting lots of code in getters/setters. If it takes more than a handful of lines, you should probably make a method rather than a property, simply because it gives a greater hint to others using your code that something big is going to happen.

Peter Leppert
A: 

Like others mentioned, use getters/setters when you want the object members to be available to other objects.

Additionally, the readability of yoru code could be improved (if you're on .NET 2.0 or greater) using autoproperties. The examples you have would then be like this:

// example 1
public static bool IsInitialEditMapPageLoad { get; set; }

// example 3/4 - note that false is the default for bools
public static bool IsInitialEditMapPageLoad { get; private set; }

Example 3 would likely stay the same, due to the validation logic being there.

SnOrfus