2

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($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'm currently making use of Style 1. Though I'm not quite sure if its the right one.

3
  • 1
    Are these really stylistic differences? Commented Oct 14, 2009 at 8:18
  • 1
    Honestly, I wouldn't know which style to choose. I'd say it would not make much difference. Commented Oct 14, 2009 at 8:19
  • The different styles should show varying degrees of readability. Though the differences aren't really obvious to me since I'm the one coding 'em. That's why I'm asking this question. Commented Oct 14, 2009 at 9:55

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

By definition else if always has a different condition than the preceding if, so your objection doesn't make sense :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.