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?
The purpose of validation, as a generic action, is to establish the compliance of any activity output as compared to inputs of the activity. It is used to provide information and evidence that the transformation of inputs produced the expected and right result.
In the Java programming language, the most natural way of doing data validation seems to be the following: try to build an object. if no problem is found, then just use the object. if one or more problems are found, then ensure the caller has enough information to tell the user about the issues.
Defines a helper class that can be used to validate objects, properties, and methods when it is included in their associated ValidationAttribute attributes.
Another way to create a class in Python is using @dataclass. Dataclass provides a decorator for automatically generating __init__() method. Besides, @dataclass also introduces a special method called __post_init__() , which is invoked from the hidden __init__() .
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.).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With