I understand that creating public properties that control private fields is good practice because of coupling and encapsulation, although lately I have seen it as such a waste of boilerplate code for a simple entity class like below.
Take this class for instance,
public class PersonEntity
{
private string _firstName;
private string _lastName;
private int _age;
public class PersonEntity(string firstName, string lastName, int age)
{
_firstName = firstName;
_lastName = lastName;
_age = age;
}
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
public int Age
{
get { return _age; }
set { _age = value; }
}
}
If all I am using is the property, is it okay to refactor the class to look something like this?
public class PersonEntity
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public class PersonEntity(string firstName, stirng lastName, int age)
{
FirstName = firstName;
LastName = lastName;
Age = age;
}
}
Or maybe even this is more simple (using object initialization to construct):
public class PersonEntity
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
Which one should I implement if all I want to use the entity for is to map data from a database, and use it as a model to write to the database at a later date than when it was created?
Which versions should I use, when should I use them, and for what reasons should I use each one?
public T Name { get; set; }
properties are called Auto-Implemented Properties. The compiler creates the private backing field for you so they are just a convenience. I'd say 100% use it for simple properties like you've shown. \$\endgroup\$