Let’s say I have a class like:
class NavigationData
{
float roll;
float pitch;
double latitude;
double longitude;
}
and if I want to create a method:
const bool validate() const;
which basically validates whether the 4 fields contain valid values.
Should validate() be part of NavigationData class, or should I create something like a NavigationDataValidator, that contains a validate(const NavigationData&) method.
I’m just giving a simple example, obviously my real class is a lot more complicated than this. I’m looking for good OO principles.
Put it another way: given a method, how do we know if it should belong to the class, or should belong to a separate class?
Typically it is a class’s own responsibility to ensure that it maintains a logically consistent and valid internal state. For instance,
Personmay have a constructor that requires both a first and last name if operations onPersonare 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,
PersonValidatormay require thatPersonhas a phone number which is in the US. ButPersonshouldn’t necessarily need to know anything about whether or not aPhoneNumberis 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.).