开发者

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? or suggest something better? thanks

Style 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

public function register($user, $pass) {
 if($this->model->isRegistered($use开发者_C百科r)
 {
  return false;
 }

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

 return false;
}

Style 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.


I don't want to sound too rude but I like noone of the 3 proposed styles. 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.


In Style 1 "if" and "else if" is used on different conditions, so it doesn't make sense.

In Style 2 lines:

 $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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜