在编写一段并不复杂的脚本的时候,发现了一个问题。先说说代码,它的主要功能是用 PHP 判断是否生成一段 Javascript,并使用 Cookie 记录状态
/* PHP code */
header("Content-type: text/javascript");
if (!haveCookie('cookieName')) {
// ... do something
?>
/* Javascript code */
if ('undefined' == typeof document.cookie['cookieName']) {
setCookie('cookieName', 3600);
}
// ... do something with Javascript
}
?>
粗看起来代码已经无懈可击,我们亲爱的 小马 还是发现了问题的存在。就是在 Javascript 中的那个判断是永远为 true
if ('undefined' == typeof document.cookie['cookieName']) {
// ...
}
因为这段代码是在 PHP 端有个前提,就是
if (!haveCookie('cookieName'))的时候,才会在客户端显示。那么,当不满足这一条件,这段代码自然就不会扔给客户端。这样说似乎有点笼统,那么先撇开 Javascript 代码,我们就单纯使用 PHP 代码表述一下
header("Content-type: text/javascript");
if (!haveCookie('cookieName')) {
if (!haveCookie('cookieName')) {
setCookie('cookieName');
}
}
?>
这样就显得清晰了很多,并很容易就能发现问题所在 -- 我们在不经意间就多做了一次判断,虽然这是 Javascript 在客户端执行的。
总结下,本人从这段代码想到的些废话:
1.代码越长,不见得效率就越高
2.在不影响逻辑和流程的情况下,尽量将多个判断写在一起
3.尽量将低复杂度的函数放前判断
4.过多的判断容易造成程序效率降低,在判断中使用高时间复杂度的函数时尤其要注意
5.如果发现 if 嵌套得太多,就得重新考虑流程和算法
6.健壮的代码不是靠过分的判断保证而成的
7.将代码简化后,会发现很多还未发现的问题
8.过多的判断另个角度理解,是缺乏对代码的信心

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version
Visual web development tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version
Recommended: Win version, supports code prompts!

WebStorm Mac version
Useful JavaScript development tools
