简体   繁体   English

编码方式:功能和程序编码标准

[英]Coding style: function and procedures coding standard

Ch 7.6 of Code Complete 2 is confusing me, I've attached some sample code (in php) mind telling me which style is the best? Code Complete 2的7.6章让我感到困惑,我附带了一些示例代码(在php中),告诉我哪种风格最好? or suggest something better? 或提出更好的建议? thanks 谢谢

Style 1 样式1

public function register($user, $pass) {
 if($this->model->isRegistered($user)
 {
  return false;
 }
 else if($this->twitter->login($user, $pass))
 {
  return $this->model->addUser($user, $pass);
 }

 return false;
}

Style 2 风格2

public function register($user, $pass) {
 if($this->model->isRegistered($user)
 {
  return false;
 }

 $this->twitter->login($user, $pass);
 if($this->twitter->isLoggedIn())
 {
  return $this-model->addUser($user, $pass);
 }

 return false;
}

Style 3 风格3

public function register($user, $pass) {
 if($this->model->isRegistered($user)
 {
  return false;
 }

 $status = $this->twitter->login($user, $pass);
 if($status)
 {
  return $this->model->addUser($user, $pass);
 }

 return false;
}

I'm currently making use of Style 1. Though I'm not quite sure if its the right one. 我目前正在使用样式1。尽管我不太确定它是否正确。

I don't want to sound too rude but I like noone of the 3 proposed styles. 我不想听起来太粗鲁,但我不喜欢这3种提议的风格。 If I'm checking for conditions preventing the execution of a function, I'll always stick with this style. 如果我要检查妨碍执行功能的条件,那么我将始终坚持这种风格。 In general: 一般来说:

function action()
{
    if ($guard_condition1)
        return $failure;

    if ($guard_condition2)
        return $failure;

    do_action();
    return $success;
}

So I'd rewrite your code as following: 因此,我将您的代码重写如下:

public function register($user, $pass)
{
    if ($this->model->isRegistered($user))
        return false;

    if (!$this->twitter->login($user, $pass))
        return false;

    return $this->model->addUser($user, $pass);
}

Anyway, if you need an opinion on what you proposed, I'd vote for style 3. 无论如何,如果您对提出的建议有意见,我会投票支持样式3。

In Style 1 "if" and "else if" is used on different conditions, so it doesn't make sense. 在样式1中,“ if”和“ else if”在不同的条件下使用,因此没有意义。

In Style 2 lines: 在样式2行中:

 $this->twitter->login($user, $pass);
 if($this->twitter->isLoggedIn())

are too much hard to read in some situations but it's a proper. 在某些情况下很难阅读,但这是适当的。

For me the best one is Style 3. 对我来说,最好的是Style 3。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM