Last active
August 29, 2015 14:01
-
-
Save tonisuter/10a3a6b23773a459fb2b to your computer and use it in GitHub Desktop.
Refactoring Example: findMonth() function from Webkit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// before refactoring | |
// returns 0-11 (Jan-Dec); -1 on failure | |
static int findMonth(const char* monthStr) | |
{ | |
ASSERT(monthStr); | |
char needle[4]; | |
for (int i = 0; i < 3; ++i) { | |
if (!*monthStr) | |
return -1; | |
needle[i] = static_cast<char>(toASCIILower(*monthStr++)); | |
} | |
needle[3] = '\0'; | |
const char *haystack = "janfebmaraprmayjunjulaugsepoctnovdec"; | |
const char *str = strstr(haystack, needle); | |
if (str) { | |
int position = static_cast<int>(str - haystack); | |
if (position % 3 == 0) | |
return position / 3; | |
} | |
return -1; | |
} | |
// after refactoring | |
// returns 0-11 (Jan-Dec); -1 on failure | |
static int findMonth(const char* monthStr) | |
{ | |
ASSERT(monthStr); | |
char needle[4]; | |
for (int i = 0; i < 3; ++i) { | |
if (!*monthStr) | |
return -1; | |
needle[i] = static_cast<char>(toASCIILower(*monthStr++)); | |
} | |
needle[3] = '\0'; | |
const std::string haystack = "janfebmaraprmayjunjulaugsepoctnovdec"; | |
std::string::size_type str_pos = haystack.find(needle); | |
if (str_pos != std::string::npos) { | |
int position = static_cast<int>(str_pos); | |
if (position % 3 == 0) | |
return position / 3; | |
} | |
return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment