Let\'s say I have a class like:
class NavigationData
{
float roll;
float pitch;
double latitude;
double longitude;
}
and if I want to c
I would say it depends. If the class's data is validatable in isolation I would put the method in the class, but if the validation requires a context then I would create a validator class based on some interface.
Typically it is a class's own responsibility to ensure that it maintains a logically consistent and valid internal state. For instance, Person
may have a constructor that requires both a first and last name if operations on Person
are meaningless without this data.
However, "logically consistent and valid" is different from "makes sense in the domain", so it is sometimes the responsibility of an external class to ensure that domain rules are obeyed. For example, PersonValidator
may require that Person
has a phone number which is in the US. But Person
shouldn't necessarily need to know anything about whether or not a PhoneNumber
is in the US.
A good rule of thumb is that if state or domain rules external to the class are required in addition to the data that already belongs to the class, you will want to consider having external validation. You may also want to centralize validation in an external class if the state of the class's instances can come from multiple sources (e.g., database, web form, file, etc.).