5个不好的编程习惯(转)
原文:https://zhuanlan.zhihu.com/p/434237651
在项目的每一次提交之后,我都会进行大量代码审查,会经常看到一些重复出现的错误。
以下这五个错误应该要及时纠正,这是纠正它们的方法。
这5个PHP编程中的不良习惯,一定要改掉!
1、测试循环前数组是否为空?
copy$items = [];
// ...
if (count($items) > 0) {
foreach ($items as $item) { // process on $item ...
}}
foreach循环或数组函数(array_*)可以处理空数组。
- 不需要先进行测试
- 可以减少一层缩进
copy$items = [];
// ...
foreach ($items as $item) { // process on $item ...
}
2、将方法的所有内容封装在if语句中
copyfunction foo(User $user) {
if (!$user->isDisafunction foo(User $user) {
if (!$user->isDisabled()) {
// ...
// long process
// ...
}
}bled()) {
// ...
// long process
// ...
}
}
这不是特定于PHP的,但我经常看到它。你可以通过提前返回,来减少缩进级别的极简代码!
该函数的所有“有用”主体现在处于第一个缩进级别
copyfunction foo(User $user) {
if ($user->isDisabled()) {
return;
} // ...
// long process
// ...
}
3、多次调用isset方法
copy$a = null;
$b = null;
$c = null;
// ...
if (!isset($a) || !isset($b) || !isset($c)) {
throw new Exception("undefined variable");
}
// or
if (isset($a) && isset($b) && isset($c) {
// process with $a, $b et $c
}
// or
$items = [];
//...
if (isset($items['user']) && isset($items['user']['id']) {
// process with $items['user']['id']
}
我们经常需要检查是否已定义变量(而不是null)。
在PHP中,我们可以使用isset函数来做到这一点。而且该函数一次可以接受多个参数!
copy$a = null;
$b = null;
$c = null;
// ...
if (!isset($a, $b, $c)) {
throw new Exception("undefined variable");
}
// or
if (isset($a, $b, $c)) {
// process with $a, $b et $c
}
// or
$items = [];
//...
if (isset($items['user'], $items['user']['id'])) {
// process with $items['user']['id']
}
4、echo方法和sprintf结合使用
copy$name = "John Doe";
echo sprintf('Bonjour %s', $name);
这段代码可能在微笑,但是我碰巧写了一段时间。而且我仍然看到很多!
除了结合echo和sprintf,我们可以简单地使用printf方法。
copy$name = "John Doe";
printf('Bonjour %s', $name);
5、通过组合两种方法检查数组中键的存在
copy$items = [
'one_key' => 'John',
'search_key' => 'Jane',
];if (in_array('search_key', array_keys($items))) {
// process
}
最后一个错误我看到的往往是联合使用in_array和array_keys。
所有这些都可以使用array_key_exists替换。
copy$items = [
'one_key' => 'John',
'search_key' => 'Jane',
];if (array_key_exists('search_key', $items)) {
// process
}
我们还可以使用isset来检查值是否是null。
copyif (isset($items['search_key'])) {
// process
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构