纵深防御与 DRY 的比较

发布于 2024-10-19 21:44:28 字数 357 浏览 2 评论 0原文

“纵深防御”原则指出,应该在多个地方强制执行约束,这样,如果一条数据绕过或漏过一层,就会被下一层捕获。一个很好的例子是在 Web 应用程序中 - 您将验证放入客户端 JavaScript、服务器端代码(PHP/Ruby/ASP/其他)中,然后将这些规则放入数据库中(例如外键约束)。这样,任何通过 JavaScript 验证的数据都会被服务器端捕获。任何通过服务器验证的数据都会受到数据库约束的捕获。

然而,这似乎违反了 DRY(Don’t Repeat Yourself)原则。这里有三个地方重复相同的验证规则。我知道有多种方法可以生成客户端 JavaScript,以便强制执行服务器端验证。我的问题是,如何整合数据库约束和服务器端代码?有没有办法生成代码以自动强制执行数据库约束?

The principle of "defense in depth" states that constraints should be enforced in multiple places, so that if a piece of data bypasses or slips through one layer, it is caught in the next. A good example is in a web app - you put validation in the client side javascript, in the server-side code (PHP/Ruby/ASP/whatever), and you put those rules in the database (e.g. foreign key constraints). That way, any data that gets past the Javascript validation gets caught by the server side. Any data that gets past the server validation is caught by database constraints.

However, this seems to violate the DRY (Don't Repeat Yourself) principle. Here you've got three places where the same validation rules are being repeated. I understand that there are ways to generate client side javascript such that it enforces server-side validation. My question is, how does one consolidate database constraints and server-side code? Is there any way to generate code such that it automatically enforces database constraints?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

后eg是否自 2024-10-26 21:44:28

我们的做法是让单个模块成为“安全规则”的所有者,然后为其创建一个 AJAX 接口,以便服务器端代码直接调用它,然后前端 UI 组件调用该 AJAX 接口,但它们都在与同一个模块通信。通过这种方式,访问规则仅存在于一个位置(安全模块),并且您仍然可以在任何地方强制执行这些规则。这样做的另一个好处是可以将规则保留在客户端可下载代码之外。

We've done this by making a single module the owner of the "security rules", then creating an AJAX interface for it as well, so that the server-side code calls it directly, then front-end UI components call the AJAX interface, but they're all talking to the same module. In this manner, the access rules are only ever in one place (the security module) and you still enforce the rules everywhere. This has an extra advantage of keeping the rules outside of the client-downloadable code.

自在安然 2024-10-26 21:44:28

DRY(不要重复自己)是一种源代码最佳实践原则,基本上意味着:不要重复代码,因为如果这样做,就会降低可维护性并增加出现错误的机会。

在数据库中强制引用完整性并不是真正违反 DRY,因为:

  • 数据库不是源代码的一部分,
  • 独立存在,
  • 除了客户端视图之外,还可以通过许多其他方式进行访问和修改。例如查询和报告引擎

DRY (Don't Repeat Yourself) is a source code, best-practices principle that basically means: do not duplicate code because if you do you'll lower maintainability and increase the chance for bugs.

Enforcing referential integrity in the database is not a real violation of DRY because:

  • a database is not part of the source code
  • stands on its own
  • can be accessed and modified many other ways besides the client-side view. E.g. querying and reporting engines
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文