Coding style: standard for coding functions and procedures
Ch 7.6 of Code Complete 2 confuses me, I have attached some example code (in php) that tells me which style is better? or suggest something better? thank
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($user)
{
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 am currently using style 1. Although I am not entirely sure if it is correct.
+2
source to share
2 answers
I don't want to sound too harsh, but I don't like any of the three suggested styles. If I check for conditions that prevent a function from being executed, I will always stick to that style. Generally:
function action()
{
if ($guard_condition1)
return $failure;
if ($guard_condition2)
return $failure;
do_action();
return $success;
}
So I would rewrite your code like this:
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 want an opinion on what you suggested, I would vote for style 3.
+3
source to share