是否有必要验证进入结果类的数据?
在我的库中,我有一个执行某些处理的类,并且此 process()
方法的返回是一个 Result
类。
例如,
class Result {
protected $data1;
protected $data2;
public function __construct($data1, $data2) {
$this->data1 = $data1;
$this->data2 = $data2;
}
// Some getters that use $data1 and $data2
}
这个 Result
类有一些 getter,用于处理 $data1
和 $data2
的返回值。
现在,要使这些 getter 工作,$data1
和 $data2
需要具有某种格式,例如字符串、多维数组等。
我的处理类将始终正确实例化 Result
,但是我是否仍然应该验证进入 Result
的数据?
如果注入无效数据并运行特定方法,那么就会出现 PHP 错误,这显然是不好的。但只有当有人用错误的数据物理实例化 Result
类时,才会发生这种情况。
我只是不想添加验证,因此当我不认为实际上需要它时会增加更多的开销。
想法?
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.
Now, 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您相信数据来源吗?如果是这样,那么不必担心验证。
另一方面,如果这些数据来自不受信任的来源(一个主要示例:用户从网页提供的数据),那么是的,您绝对应该验证输入。
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.