Is it necessary to validate data going into a result class?
In my library I have a class that does some processing, and the return of this process()
method is a Result
class.
For example,
class Result {
protected $data1;
protected $data2;
public function __construct($data1, $data2) {
$this->data1 = $data1;
$this->data2 = $data2;
}
// Some getters that use $data1 and $data2
}
This Result
class has some getters on it that process $data1
and $data2
for their returns.
N开发者_StackOverflow社区ow, for these getters to work $data1
and $data2
will need to be of a certain format, e.g. string, multi-dimensional array, etc.
My processing class will always instantiate Result
correctly, but should I still be validating the data going into Result
anyway?
If invalid data is injected and a particular method is run, then a PHP error will occur, which is obviously bad. But that will only happen if someone physically instantiates the Result
class with erroneous data.
I just don't want to add validation, and therefore more overhead, when I don't believe it's actually required.
Thoughts?
Do you trust the source of the data? If so, then don't worry about validation.
On the other hand, if this data comes from an untrusted source — a prime example: user-provided data from a web page — then yes, you absolutely should validate the input.
In my opinion, you should theoretically. If this would be a question asked to you in classroom the answer should be yes, you never know which corner cases occur, or maybe someone else has to maintain the application you create and can possibly break the application.
However, in practice your customer and employer would rather see working software then (for them at least) a lot of lines of code that never really does anything. I would just write it on my to do list and do something of higher priority.
精彩评论