This course will be retired on June 1, 2025.
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
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
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