3

Following OOP's best practices, is it better to have this code:

class Car {

    private Driv driver;

    public Driv Driver {

        get { return driver; }

        set { driver = value; }
    }

}

Or this one?

class Car
{
    public Driv Driver { get; set; }
}

While the second version is shorter, I feel like I'm breaking the main premise of the Encapsulation concept:

EVERY class should keep its privates to itself.

Hope the answer is not too trivial.

  • 2
    If you don't create an instance of the private variable itself, the code does it for you, even though you never see it. – ProgrammingDude Feb 24 '16 at 18:35
  • 1
    I understand. But then it's exactly the same using one version or another, right? With the difference that the second is shorter. – Jose Lopez Garcia Feb 24 '16 at 18:36
  • If we needed additional logic, then we would need the first version. Am I right? – Jose Lopez Garcia Feb 24 '16 at 18:37
  • 1
    Yeah, that is the only difference. However, if you use stuff like INotifyPropertyChange then you pretty much have to include the private variable. – ProgrammingDude Feb 24 '16 at 18:37
  • 1
    Personally I prefer auto properties because its less code so makes the file easier to read (less clutter). Other than that there is no difference. Do whatever makes you feel good. – Igor Feb 24 '16 at 18:38
  • But if I needed additional logic, then I'd need to explicitly define the Field right? – Jose Lopez Garcia Feb 24 '16 at 18:38
  • Possible duplicate: [Difference between Property and Field in C# 3.0+](http://stackoverflow.com/questions/653536/difference-between-property-and-field-in-c-sharp-3-0) – Igor Feb 24 '16 at 18:41

4 Answers4

3

Your first example is what's called a Property with a backing field

The second is called an Automatic property.

The purpose of a property with a backing field is so that you can control access to your private properties.

So... If for instance you want to, make a calculation before returning the value of your private field, you could do it in the one with the backing field.

Or lets say you have a car object with 10,000 miles on the clock... you would probably want to only increment its value using the Drive method, and hide the setter of the Property with the backing field

void Main()
{
    var car = new Car();
    car.Drive();
    Console.WriteLine (car.Miles);
}

public class Car
{
    private int miles;

    public Car()
    {
        miles = 10000;
    }


    public int Miles 
    {
        get
        {   
            return this.miles;
        }
    }

    public void Drive()
    {
        this.miles += 100;
    }
}
Aydin
  • 13,406
  • 4
  • 25
  • 41
  • So when I should one over the other? Thanks! – Jose Lopez Garcia Feb 24 '16 at 18:40
  • 1
    If you don't need to have any logic validating, modifying or constricting access to your private variables... you can just use an automatic property... – Aydin Feb 24 '16 at 18:43
  • 1
    ... and an `Automatic Property` is just syntactic sugar that makes the code easier to write. As long as you do not need to do any additional actions when getting or setting the value, for example like raising OnPropertyChanged(), you don't need to explicitly define a private backing field. – GeorgDangl Feb 24 '16 at 18:43
  • Very true.. @JosePerez added an example to boot ;) – Aydin Feb 24 '16 at 18:48
3

There really is no difference. If no private variable is created by the user then the code will be generated automatically for the private field. However, if the user wishes to do additional logic in the getter or setter of the property then declaring a private field is necessary.

ProgrammingDude
  • 569
  • 1
  • 5
  • 25
  • 1
    I can only accept 1 answer. Since this user was the first one to answer it in a comment, and since the answer is simple and to the point, I'm inclined to accept it. However, all answers suggested here are as useful. – Jose Lopez Garcia Feb 24 '16 at 19:02
  • You don't have to accept because I was first. Always accept what you feel is the best answer. – ProgrammingDude Feb 24 '16 at 19:03
  • You misunderstood me. I said that your answer was short and to the point, as most answers. So I followed the first-in first-out rule to accept an answer. If you are feeling uncomfortable with my decision let me know. – Jose Lopez Garcia Feb 24 '16 at 20:35
  • No, I'm fine with it. Just didn't want you accepting my answer if you didn't feel that it was the best one. – ProgrammingDude Feb 24 '16 at 21:15
1

You are not breaking encapsulation with the second approach. The second approach is syntactic sugar to make property definition less verbose. The benefit of this approach is that in the future if you need to modify the getter or the setter, you are setup to do so and will not break the API contract.

John Koerner
  • 35,668
  • 7
  • 74
  • 128
0

C#'s properties are simply syntactic representations of some underlying methods and variables. Essentially, the compiler turns:

public int Height { get; set; }

into:

private int height;

public int getHeight() {return height;}

public int setHeight(int h) {height = h;}

So, no you are not defying OOP encapsulation, but instead syntactically simplifying it. You could also do something like public int Height {get;} which is a nice way to create an immutable class member. It simply creates the property without a set method, so only the class itself can alter it.

Now, you only need to use properties with backing fields if you wish to do additional tasks when getting or setting a variable, such as raise an event, or update another variable. The compiler would turn:

private int height;

public int Height { get {return height;} set {height = value; OnHeightChanged();} }

into:

private int height;

public int getHeight() {return height;}

public int setHeight(int value) {height = value; OnHeightChanged();}

Hope this helps!

Uncle Fungus
  • 93
  • 1
  • 10