In the book Clean Code
from Robert C. Martin are given many recommendations. Two of them are
- to keep functions small and
- within a function to only have one level of abstraction.
I already cleaned the following method up a bit by extracting a few methods (RemoveFontColor()
, RemoveTextHighlight()
). But i am not sure if the few-liners (font-style, font-weight, etc.) should be extracted into a method as well. The advise from the author is to not mix different-levels of abstraction within a function because this could lead to other details creeping in. This would mean that even the two liners will be extracted into their own methods.
The partly refactored code example
private string Fix(FixPreferences preferences,string value)
{
if (preferences.IsRemoveBold) {
value = value.Replace("font-weight:bold", "font-weight:normal");
value = value.Replace("font-weight: bold", "font-weight:normal");
}
if (preferences.IsRemoveItalics) {
value = value.Replace("font-style:italic;", "font-style:normal;");
value = value.Replace("font-style: italic;", "font-style:normal;");
}
if (preferences.IsRemoveFontColor) {
value = RemoveFontColor(value);
}
if (preferences.IsRemoveTextHighlight) {
value = RemoveTextHighlight(value);
}
if (preferences.IsRemoveStrikethrough){
value =
value.Replace("text-decoration: line-through;", "text-decoration:none;");
value =
value.Replace("text-decoration:line-through;", "text-decoration:none;");
}
if (preferences.IsRemoveUnderline)
{
value =
value.Replace("text-decoration: underline;", "text-decoration:none;");
value =
value.Replace("text-decoration:underline;", "text-decoration:none;");
}
return value;
}
Update
I changed to extract even the few lines - but it still looks not pretty.
private string Fix(ChangeLogFixOperationPreferences preferences,string value)
{
if (preferences.IsRemoveBold)
value = RemoveBold(value);
if (preferences.IsRemoveItalics)
value = RemoveItalics(value);
if (preferences.IsRemoveFontColor)
value = RemoveFontColor(value);
if (preferences.IsRemoveTextHighlight)
value = RemoveTextHighlight(value);
if (preferences.IsRemoveStrikethrough)
value = RemoveStrikethrough(value);
if (preferences.IsRemoveUnderline)
value = RemoveUnderline(value);
if (preferences.IsResetFontSize)
value = ResetFontSize(value);
return value;
}
Is there a better way - for example to put the preferences and the methods into a dictionary and for each preference that is set to true the function from the dictionary is called within a loop?
My question
- How would you refactor the code above?
- Are there any ways to group the different
font-*
ortext-decoration:*
togehter in one function? Would that be wise since it violates the single responsibility pattern (SRI)? - Update: Would you recommend calling a function from a dictionary
- store functions in a dictionary or may be
- call method dynamically or
- from Jon Skeet storing functions in a dictionary by using Action