Skip to content

Instantly share code, notes, and snippets.

@tonisuter
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonisuter/10a3a6b23773a459fb2b to your computer and use it in GitHub Desktop.
Save tonisuter/10a3a6b23773a459fb2b to your computer and use it in GitHub Desktop.
Refactoring Example: findMonth() function from Webkit
// 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