Control write access to class attributes.
Separate data from methods that use it.
Encapsulate class data initialization.
A class may expose its attributes (class variables) to manipulation when manipulation is no longer desirable, e.g. after construction.
A class may have one-time mutable attributes that cannot be declared final.
The motivation for this design pattern comes from the design goal of protecting class state by minimizing the visibility of its attributes (data).
The private class data design pattern seeks to reduce exposure of attributes by limiting their visibility.
public class EmployeeData
{
public Guid Id { get; private set; }
public string FirstName { get; private set; }
public string LastName { get; private set; }
public EmployeeData(Guid id, string firstName, string lastName)
{
Id = id;
FirstName = firstName;
LastName = lastName;
}
}
public class Employee
{
private EmployeeData _EmployeeData;
public Employee(EmployeeData employeeData)
{
_EmployeeData = employeeData;
}
public string SimpleId => _EmployeeData.Id.ToString().Replace("-", string.Empty);
public string FullName => string.IsNullOrEmpty(_EmployeeData.FirstName)
? _EmployeeData.LastName
: $"{_EmployeeData.FirstName} {_EmployeeData.LastName}";
}