"Object-Oriented Objective-C" was retired on May 31, 2020.
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!
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