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'd say have it validate itself as long as the valid values don't depend on what other classes use NavigationData.
Basically, as long as latitude and pitch has to always be between +/- 90 degrees, and longitude and roll always be between +/- 180 degrees, keep the validator in the class.
(By the way, what about heading?)
It depends on the context. Sometimes, your object is absolutely valid internally, but in the context its values aren't acceptable.
If you have simple Data Transfer Object then it probably shouldn't validate itself.
If you have a class of Domain Model then it should do some validation.
P.S. just my personal preference: isValid () instead of validate () when method returns boolean value.
The right answer is: it depends.
The natural place to put such object logic is in the object itself. Sometimes though the validation rules could be dependent on a rules engine or some kind of larger "framework" which validates stuff. Another situation where you wouldn't want to do validation inside the object is when validation belongs in another tier, or layer or the application, such as the view layer.
Your class should be designed such a way and provide such methods that validate() is always true:
Such validate() methods are called class invariants and are important part of Design by Contract.
Depends...
Sometimes the validations are not part of the class itself, but business logic, and adding it to the class would prevent reutilization, and therefore, the usage of a validating class is good. Otherwise, the class should be able to validate itself.
As it has already been said, it depends.
But in your case, I would go for a different solution, create new immutable class for geo coordinates
class GeoCoordinates
{
double Latitude;
double Longitude;
}
And let this class validate that latitude and longitude are within valid limits. You will probably need this other places as well, for example.
class Airport
{
GeoCoordinates Location;
...
}