- Clean Code in C#
- Jason Alls
- 336字
- 2025-04-04 12:56:14
Objects should hide data and expose methods
The state of your object is stored in member variables. These member variables are data. Data should not be directly accessible. You should only provide access to data via exposed methods and properties.
Why should you hide your data and expose your methods?
Hiding data and exposing methods is known in the OOP world as encapsulation. Encapsulation hides the inner workings of a class from the outside world. This makes it easy to be able to change value types without breaking existing implementations that rely on the class. Data can be made read/writable, writable, or read-only providing more flexibility to you regarding data access and usage. You can also validate input and so prevent data from receiving invalid values. Encapsulating also makes testing your classes much easier, and you can make your classes more reusable and extendable.
Let's look at an example.
An example of encapsulation
The following code example shows an encapsulated class. The Car object is mutable. It has properties that get and set the data values once they have been initialized by the constructor. The constructor and the set properties perform the validation of the parameter arguments. If the value is invalid, an invalid argument exception is thrown, otherwise the value is passed back and the data value is set:
using System;
namespace CH3.Encapsulation
{
public class Car
{
private string _make;
private string _model;
private int _year;
public Car(string make, string model, int year)
{
_make = ValidateMake(make);
_model = ValidateModel(model);
_year = ValidateYear(year);
}
private string ValidateMake(string make)
{
if (make.Length >= 3)
return make;
throw new ArgumentException("Make must be three
characters or more.");
}
public string Make
{
get { return _make; }
set { _make = ValidateMake(value); }
}
// Other methods and properties omitted for brevity.
}
}
The benefit of the preceding code is that if you need to change the validation for the code that gets or sets the data values, you can do so without breaking the implementation.