Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Well done!
You have completed Getting Started with PHP Unit Testing!
You have completed Getting Started with PHP Unit Testing!
Preview
Refactoring restructures the code, without changing its behavior.
Download the completed sample files
Multiple Iterations of the Same Code
Option 1: List of elseif statements
if (in_array($firstThreeLetters, $this->trigraphs)) {
$newWord = substr($word, 3);
$newWord .= $firstThreeLetters . 'ay';
} elseif (in_array($firstTwoLetters, $this->digraphs)) {
$newWord = substr($word, 2);
$newWord .= $firstTwoLetters . 'ay';
} else {
$newWord = substr($word, 1);
$newWord .= $firstLetter . 'ay';
}
return $newWord;
Option 2: Early Return
if (in_array($firstThreeLetters, $this->trigraphs)) {
return substr($word, 3) . $firstThreeLetters . 'ay';
}
if (in_array($firstTwoLetters, $this->digraphs)) {
return substr($word, 2) . $firstTwoLetters . 'ay';
}
return substr($word, 1) . $firstLetter . 'ay';
Option 3: Switch Statement
switch (true) {
case in_array($firstLetter, $this->vowels):
$newWord = $word . 'ay';
break;
case in_array($firstThreeLetters, $this->trigraphs):
$newWord = substr($word, 3);
$newWord .= $firstThreeLetters . 'ay';
break;
case in_array($firstTwoLetters, $this->digraphs):
$newWord = substr($word, 2);
$newWord .= $firstTwoLetters . 'ay';
break;
default:
$newWord = substr($word, 1);
$newWord .= $firstLetter . 'ay';
}
return $newWord;
Option 3b: Switch Statement Early Return
switch (true) {
case in_array($firstLetter, $this->vowels):
$newWord = $word . 'ay';
return $newWord;
case in_array($firstThreeLetters, $this->trigraphs):
$newWord = substr($word, 3);
$newWord .= $firstThreeLetters . 'ay';
return $newWord;
case in_array($firstTwoLetters, $this->digraphs):
$newWord = substr($word, 2);
$newWord .= $firstTwoLetters . 'ay';
return $newWord;
default:
$newWord = substr($word, 1);
$newWord .= $firstLetter . 'ay';
return $newWord;
}
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
Refactoring restructures the code
without changing its behavior.
0:00
I don't like having this long list of else
if statements, so I want to change that.
0:04
I could use a switch statement, but
I like having early returns in my methods.
0:10
As soon as a condition is met,
I want to return the results.
0:15
At the end of our first conditional block,
we can return $newWord.
0:19
Now instead of an else if, I can make this
second conditional a separate conditional.
0:27
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up