Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining both Private Field and Property vs just Property

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.

like image 935
Jose Lopez Garcia Avatar asked Dec 24 '22 08:12

Jose Lopez Garcia


1 Answers

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.

like image 97
ProgrammingDude Avatar answered Apr 30 '23 07:04

ProgrammingDude