Defensive Programming in PHP(PHP中的防御性编程)

觉得这篇文章写得很不错 不关乎php觉得其他的语言也是针对的,看完这篇文章有所收获

What Does “Defensive Programming” Mean?

Defensive programming, simply put, is programming with the intent to anticipate likely failure points. The goal is to circumvent those likely problems before they occur. You see the problem, right? There’s something inherently difficult with the advice “expect the unexpected” and it’s made many times worse when one alters it to “expect the unexpected and try to prevent it”.

Let’s look at some practical examples.

Conditional Statements

This is one of the easiest places to program defensively, and one where it’s easiest to be complacent. In many cases while programming in PHP, you simply won’t need an “else” case.

Hypothetically, you are working on a function and need a conditional. You only have three possible states for your particular variable at this point – and you have those covered in a block like this:

if($var == a){ }
else if($var == b){ }
else if($var == c){ }

There are no other possibilities, you say, and you move on with your code. Let me stop you there, though. I know that you know there are no other possibilities. And I believe you. But sometimes (unexpected) things happen. We forget about something. We look over mistakes. We end up reusing a bit of code outside of its originally intended scope. And all of a sudden we have leaking and sometimes silent error states because there’s no catch here. Make use of else blocks. Make use of default in switches. Use them to return or log an error so that you’re aware of what’s happened, should it ever happen. It may be an extra couple of lines of code, but it’s worth it when something happens that you did not expect.

Never Trust User Input

Have you heard this statement before? Most programmers have. It is a bit of a vague, generalized thing to say, granted. But it’s true. You should never trust user input. This does not mean that you assume that all users are crazed hackers out to destroy your application with a single set of well crafted commands. There is no need for paranoia. But, you should assume that users don’t know your code. They don’t know what parameters you need filled or how long the input can be. They don’t know what file types they can upload (even if the app tells them) or what size. And occasionally, they are a bot or a hacker and they are going to be trying to run scripts in their inputs. Sometimes even from inputs behind a login wall. How do you know when you can trust things like authentication or captchas to provide a safe barrier before users arrive at input forms?

The answer: Never.

If you never trust user input, then you never have a breach because you trusted user input. See? So always validate your input, and always ensure that you’re using appropriate techniques when handling data, especially when storing it in the database or retrieving it for display. For that matter – don’t trust input at all, even when from somewhere besides your users – input validation is always your friend. Check outSurvive the Deep End: PHP Security and look into using a validation library.

Assumptions About Your Code

Don’t assume anything. If the previous two topics teach us anything, it’s that we should not make any assumptions. As programmers, especially when focusing on a single project for too long, we begin to assume a lot. We begin to assume that the user knows some of the things we know. Not necessarily technical details, but functional details about the program. We assume that the user will know how big files can be because… we already know that fact. Or that they’ll know that in order for the mailing script to… but no, they have no idea about any of that. This can sometimes matter more for front-end work, but obviously you still deal with user behavior and user input in the back-end as well, so it’s worth thinking about.

Another staggering assumption that many programmers make is the assumption of the obvious nature of our functions, classes, or whatever other bit of code we’re working on at any given time. A defensive programmer will try to think carefully about not only normal documentation and describing what a bit of functionality does – but they will also document any assumptions they are making about input, parameters, use cases, or any number of other similar things. Because we are all humans, and we sometimes forget things later. We also will all most likely end up with someone maintaining, extending, or replacing our code someday. If nothing else, recall that programming is happening in a world full of technological changes. If your application is still around in several years, it may need to be updated to a newer version of PHP and lose some of its functionality, or any number of components that it interacts with may change and necessitate changes in your own code. It is very difficult to predict these things, so good comments and documentation are very important.

Tunnel Vision

Another thing that can cause us to both forget good commenting practices as well as standards is tunnel vision. Tunnel vision happens a lot to programmers. You know the feeling. You’re solving a problem, you’re in the groove. You’re feeling isolated in your own little world, with your music (or lack thereof) and you’re just coding and all of a sudden two hours have passed since you last checked the clock and you realize that you’ve written countless lines of code without any comments. It happens to all of us at one time or another, but the important thing is to, at some point, catch that and add some where appropriate.

Consistency in Syntax and Naming

Consistency is a bit of a grey area – that delves a bit more into coding standards and the like, but it is relevant to defensive programming. In PHP, there are standards that can be followed to streamline your code for others who might view it, or for your own future use. But often, no one is actually making you code to standard. However, whether you’re coding to some set of standards or not, you should at very least be internally consistent – because it will make you less error prone. This applies especially to small syntax errors that take an aggravating amount of time to return to and fix after being caught. If you always use the same spacing, the same formats and syntax, naming conventions, etc., than you are less likely to make a mistake resulting in your misreading of your own code. You are also more likely to be able to quickly scan and find things that you need to find.

Conclusion

Beyond user behaviors and actions, don’t assume anything in general about your program. Assumptions are one of the biggest enemies of a defensive programmer. Don’t assume you won’t need that default case or else statement. Don’t avoid creating appropriate user error messages, alerts, logs, and whatever else you need just because you assume they won’t be needed. Your assumptions are often right – but we do not care about that. What we care about are the times that they are wrong. Always plan as though you may need to return to your code in a few hours, weeks, months or even years, or that someone else will – and document it accordingly. Don’t assume it will never need to be updated, extended, or maintained. That’s naive at best, and negligent in more cases than not. Sometimes just keeping the idea of defensive programming in the back of your mind can help you to estimate, plan, and program more effectively and more safely.

译文:

防御性编程是什么意思

防御性编程,简单的说,就是在编程的时候有目的地预测可能的故障点。目的是在那些可能发生的问题发生前解决它们。你看见了问题,对吧?预测意料之外的事情本来就有内在的难度,当你想要预测意料之外的事情并且解决它就更是难上了好几倍。

下面我们看几个实际的例子。

条件语句

这是最容易进行防御性编程的地方之一,也是最容易满足的地方。在用PHP编程的许多情况下你不会需要“else”。

假设,你在写一个函数并且需要一个条件语句。在这里,你只需要为你特定的变量使用三个条件语句如下:

if($var == a){ }
else if($var == b){ }
else if($var == c){ }

没有其他可能性了,你说,并且继续码代码。但是,让我们在这里停一下。我知道你知道这里没有其他可能性了。并且我相信你。但有时候(不可预测的)情况会发生。我们忘掉了一些情况。我们检查错误。我们最终重用了一些代码,超出了原本的预定范围。突然我们有了泄露错误或者有时候是静默的错误状态,因为我们没有使用catch。使用else代码块。在使用switch时要使用default。用它们来返回或者记录错误,这样你才知道发生了什么(如果发生了的话)。虽然会多用两行代码,但当一些你无法预测的事情发生时,这是值得的。

绝不相信用户输入

你以前有没有听说过这个说法?大多数程序员听过。这有一点含糊,通俗点讲,理所当然。但它是真理。你绝不应该相信用户输入。这不是说你假设所有用户是疯狂的黑客,他们使用一些精心设计的命令来摧毁你的应用。没有必要妄想。但是,你应该假设用户不知道你的代码,他们不知道你需要填写什么参数,或者参数应该多长。他们不知道什么文件类型或者什么大小能上传(即使应用告诉了他们)。偶尔他们会是机器或者黑客并且他们希望在他们的输入中运行脚本,有时候甚至是在登陆后的输入中。你怎么知道你能相信认证或者验证码能在用户输入之前提供一个安全的堡垒?

答案:绝不。

你绝不相信用户输入。如果你信任的用户输入,那么你永远不会有一个突破。明白了吗?所以总是要评估你的输入,一定要保证你在处理数据尤其是要存入数据库或者要把它展示出来时使用了合适的技术。因此 – 绝不相信输入,即使来自不是用户的输入的地方 – 输入验证永远是你的朋友。看看Survive the Deep End: PHP Security 并且使用 validation library.吧。

对你的代码的假设

不要假设任何事情。如果前两个主题教会我们一些事情的话,那就是我们不应该做任何假设。作为程序员,尤其是致力于一个项目太久后,我们开始做很多假设。我们假设用户知道一些我们知道的事情。不一定是技术细节,也可以是程序的功能性细节。我们假设用户知道文件能有多大因为。。。我们已经知道。或者他们知道为了让邮件脚本。。。但事实不是,他们不知道以上任何东西。这好像更多的是前端的工作,但明显的是你在后端仍然要处理用户行为和用户输入,所以值得好好想想。

另一个许多程序员都会做的惊人的假设是我们在任何时候对于我们的函数,类或者其它代码段的明显的功能属性。一个具有防御性的程序员会仔细考虑的不仅仅是用一般的文档来描述函数是干什么的——他们也将写下他们对输入,参数,用例,或任何其他类似的东西做出的任何假设。因为我们都是人,我们过一段时间会忘掉一些事。我们最后也很可能会面临其他人维护,扩展或者替换我们的代码。如果没有别的,回想一下,编程是发生在一个充满技术变革的世界里。如果你的应用仍然能使用几年,可能会升级PHP版本并且失去一些功能,或者一些你自己代码里面具有交互的组件之间需要改变。预测这些是很困难的,所以好的注释和文档是非常重要的。

视野狭窄

另一件可以使我们忘记好的评论实践以及标准的东西是视野狭窄。许多程序员都具有视野狭窄的毛病。你知道这种感觉 - 你解决问题,你处于最佳状态。你觉得与你的音乐(或没有)独立于自己的小世界中,并且你就在编码,突然两小时过了,你意识到你已经写了无数行没有注释的代码。我们所有人偶尔都会遇到这种事情,但重要的是在某处发现这个情况并且补上应有的注释。

语法和命名的一致性

一致性是一个灰色地带 – 它更多的是关于编码标准之类的,但它和防御性编程也有联系。在PHP中,有标准规范你的代码格式以便别人查看,或者你以后使用。但常常没人让你的代码标准化。但是无论你是否按照标准编码,你至少要保持一致性 – 这能让你少犯错误。这对于需要大量时间返回并且修复的小的语法错误尤其适用。如果你总是使用相同的间隔,格式和语法,命名规格等等你就能更好的避免犯错以至于误读你自己的代码。你更可能快速浏览代码并且找到你需要的东西。

总结

总的来说,除去用户行为和动作,不要对你的程序做任何假设。假设是具有防御性编程习惯的程序员最大的敌人。不要假设你不需要 default 语句或者 else 代码块。尽量使用正确的用户错误信息,警告,日志或者任何其它你假设不会用到的代码。你的假设通常是正确的 – 但我们不在乎。我们在乎的是它们出错的时候。一定要计划得好,准备着你可能需要在几小时,几周,几个月甚至几年后回顾你的代码,或者其他人需要 – 相应的就要好好写文档。别假设它永远不需要升级,扩展或者维护。那是无知的,在更多的情况下是疏忽。有时候保持一颗防御性编程的心能帮你更有效更安全地估计,计划和编程。

译文链接:http://www.codeceo.com/article/php-defensive-programming.html
英文原文:Defensive Programming in PHP
翻译作者:码农网 – 邱康
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章