编程

Laravel 代码简洁之道(Clean Code)

976 2022-01-10 16:06:10

干净的代码是微观层面不断做出正确决策的结果。

使用表查找

不要编写重复的 else if 语句,而是使用数组根据您拥有的键查找所需值。代码将更清晰且更具可读性,如果出现问题,您将看到可以理解的异常。 没有半途而废的边缘情况。

// 不好的
if ($order->product->option->type === 'pdf') {
   $type = 'book';
} else if ($order->product->option->type === 'epub') {
   $type = 'book';
} else if ($order->product->option->type === 'license') {
   $type = 'license';
} else if ($order->product->option->type === 'artwork') {
   $type = 'creative';
} else if $order->product->option->type === 'song') {
   $type = 'creative';
} else if ($order->product->option->type === 'physical') {
   $type = 'physical';
}
if ($type === 'book') {
   $downloadable = true;
} else if ($type === 'license') {
   $downloadable = true;
} else if $type === 'creative') {
   $downloadable = true;
} else if ($type === 'physical') {
   $downloadable = false;
}

// 正确的
$type = [
   'pdf'      => 'book',
   'epub'     => 'book',
   'license'  => 'license',
   'artwork'  => 'creative',
   'song'     => 'creative',
   'physical' => 'physical',
][$order->product->option->type];
$downloadable = [
   'book'     => true,
   'license'  => true,
   'creative' => true,
   'physical' => false,
][$type];

尽早返回

通过尽早返回值来避免不必要的嵌套。过多的嵌套和 else 语句往往会使代码难以理解。

// 糟糕的示例
if ($notificationSent) {
 $notify = false;
} else if ($isActive) {
 if ($total > 100) {
   $notify = true;
 } else {
   $notify = false;
 } else {
   if ($canceled) {
     $notify = true;
   } else {
     $notify = false;
   }
 }
}
return $notify;

// 推荐的示例
if ($notificationSent) {
 return false;
}
if ($isActive && $total > 100) {
 return true;
}
if (! $isActive && $canceled) {
 return true;
}
return false;

正确分割线

不要在随机的地方分割线,但也不要让它们太长。 使用 [ 打开数组并缩进值往往效果很好。 与长函数参数值相同。 其他拆分行的好地方是链式调用和闭包。

// 糟糕的示例
// 没有分行
return $this->request->session()->get($this->config->get('analytics.campaign_session_key'));
// 无意义分行
return $this->request
 ->session()->get($this->config->get('analytics.campaign_session_key'));

// 推荐的示例
return $this->request->session()->get(
 $this->config->get('analytics.campaign_session_key')
);
// 闭包
new EventCollection($this->events->map(function (Event $event) {
 return new Entries\Event($event->code, $event->pivot->data);
}));
// 数组
$this->validate($request, [
 'code' => 'string|required',
 'name' => 'string|required',
]);

不要创建没用的变量

可以直接传值,就不要创建没用的变量。

// 坏的
public function create()
{
 $data = [
   'resource' => 'campaign',
   'generatedCode' => Str::random(8),
 ];
 return $this->inertia('Resource/Create', $data);
}

// 好的
public function create()
{
 return $this->inertia('Resource/Create', [
   'resource'      => 'campaign',
   'generatedCode' => Str::random(8),
 ]);
}