The reason for get/set functions

tgabe213

2[H]4U
Joined
Aug 27, 2007
Messages
3,684
I've never really understood this. And I'm sure it holds great value. I just don't understand what.

I was browsing for a code example of something, and that's what this is from. Why so many get/set's ?

Code:
using System;

/// <summary>
/// Summary description for Person
/// </summary>
public class Person : IPerson
{
    private int _ID;
    private string _firstname;
    private string _lastname;
    private bool _isChristian;

    public int ID
    {
        get { return _ID; }
        set { _ID = value; }
    }

    public string Firstname 
    {
        get { return _firstname; }
        set { _firstname = value; }
    }

    public string Lastname
    {
        get { return _lastname; }
        set { _lastname = value; }
    }

    public bool IsChristian
    {
        get { return _isChristian; }
        set { _isChristian = value; }
    }

    public Person()    {}

    public override string ToString()
    {
        string returnValue = @"ID: " + this.ID.ToString() + "<br />"
                            + "Firstname: " + this.Firstname + "<br />"
                            + "Lastname: " + this.Lastname + "<br />"
                            + "Is Christian: " + this.IsChristian.ToString();
        
        return returnValue;
    }
}
 
i may be wrong but i beleive previously it was a requirement of .net 1.0 but is now auto matic under 3?

someone correct me if im wrong

however it can be useful if a number of properties of the class depend on another. take a Date for example

Code:
    public class Date
    {
        private DateTime mDatetime;

  public Date(DateTime date)
        {
            mDatetime = date;
        }

        public DateTime Datetime
        {
            get { return mDatetime; }
            set { mDatetime = value; }
        }

        public DateTime DatetimePlusOne
        {
            get { return mDatetime.AddDays(1); }
        }

        public int Day_of_Year
        {
            get { return mDatetime.DayOfYear; }
        }

        public int Day_of_Month
        {
            get { return mDatetime.Day; }
        }

        public int Day_of_Week
        {
            get { return getDayOFWeek(mDatetime); }
        }
        public int Year
        {
            get { return mDatetime.Year; }
        }
      }

above you only need to pass one Constructor and all the others are derived automatically for you
 
Last edited:
get/set can do additional processing / indirection. (range constraints, value checking, etc).

In an object oriented system, it may be that your subclass needs to add additional processing. You can't do that with direct variable access.

If you write your code to use get/set you can add these features later. You can't add them if you access the variables directly (without rewriting to get/set, or putting checks all over the place).

It's a good idea to put the get/set boilerplate in place before you need it, instead of having to rewrite lots of code.
 
There's no requirement to implement get or set accessors in any version of .NET, unless you're coding to implement some specific pre-defined interface.

As ambientZ points out, the point is encapsulation. You can write code anywhere you'd like to set or get a value in an object of your class. If the implementation of that object changes, you just change the get or set method in one place--and you don't have to worry about breaking any consumers of that class because the implementation is encapsulated in the get or set method.

Encapsulation is one of the fundamental goals of object oriented programming.
 
So the reasons they're there are ideally for abstraction and encapsulation. You know one of those rules people like to spout about design for most OO languages - 'make your data members private and provide accessors for them, because public members are evil'. But I think you should be wary if you start seeing every member of a class being exposed via getters/setters. Could just be someone autogenerating them (since IDEs make this super easy to do). It might be good to think over the design of the class and think about whether or not some data should really be exposed via these methods, or if it would be better to use the data in some function the user can call without 'notifying' them it affects this member.

But I think the better way to look at them is : make your data private and provide an interface your users (other people working with your code) can use to work with the data members.
 
I understand your explanations, and they make more sense to me now, but, looking at my example, I ask myself again why have all the get/sets? It looks like the job is done at the end with string returnvalue.
 
the toString should have been using the getters to support the getters being overridden in subclasses.

As previously mentioned, the default get/sets were probably autogenerated.
 
Well, the sets are needed because the underlying members are private, and the constructor doesn't take any parameters :)
 
I understand your explanations, and they make more sense to me now, but, looking at my example, I ask myself again why have all the get/sets? It looks like the job is done at the end with string returnvalue.

You are correct, something like
Code:
        public DateTime Datetime
        {
            get { return mDatetime; }
            set { mDatetime = value; }
        }

really has very little value(unless you're implementing an interface). You might as well just make mDateTime a public variable if it can truly be any value.

If you were to say
Code:
        public DateTime Datetime
        {
            get { return mDatetime; }
            set 
            { 
                if(value >= mMinDate && value <= mMaxDate)
                          mDatetime = value;
                else
                          SetError(value.toString() + " is not in the accepted range";
            }
        }

is quite useful, forcing anything that attempts to set mDateTime to pass your validation - something that's not really possible if mDateTime is publicly accessible.
 
I disagree, because as code gets more complex, the first example always has the potential to become the second example. The transition from a raw member variable to the first example is tedious and expensive, and in some cases impossible.
 
Reason number Z for why you might need to be using get/set: Interfaces.
Whats in IPerson? I know in java you can only have method declerations in an interface.

If you wanted to define an interface for working with IPerson's you're going to use all get/set since you cant declare direct vars for people to access.
 
Also useful if one wants to do things like make properties read only to objects other than self. e.g. One could implement a getter but not the setter.
 
Ya, this used to really bug me in college - we were forced to use getters/setters everywhere even if it was just for a blind get/set with no error checking. Now that I've been working for a couple years, I still think there are legitimate cases where raw access is fine, but generally getters/setters are the clear way to go. It just saves you a ton of time and effort down the line for reasons mentioned in this thread. Also, it can make debugging or tracing unfamiliar code execution a little easier, ie - you can just put a breakpoint in the setter to quickly get an idea of who is calling what and when. (shrug)
 
I understand your explanations, and they make more sense to me now, but, looking at my example, I ask myself again why have all the get/sets? It looks like the job is done at the end with string returnvalue.

How would the toString help when you want to get individual attributes back?
 
Back
Top