I have inherited some code that upon first glance smells funny, but perhaps I'm reading into it... while reviewing the code I came across the following and made a note to consider refactoring the logic as I found it difficult to read and prone to errors.
if (somestring.Contains("some value")
result.add(specificString)
if (somestring.Contains("some other value")
result.add(anotherSpecificString)
if (...)
... 100's of lines...
My questions are:
Is the pattern okay as it is? At a minimum, I feel this should be reduced to a method that accepts the possible values and their replacements instead of the repeated if logic?
Where is the 'breaking point' - what I mean, how many if.. checks are okay before it is better to refactor?
What other refactors would be a good match for this pattern?
I had some vague early thoughts about somehow using pattern matching, but that does not appear to be a good fit here?
Ultimately, I think I need to take a giant step back and come back to look at this objectively...
I suggest extracting a model, eg
// Model: when "find" is found we should add "add" to result
static List<(string find, string add)> m_ToAdd =
new List<(string find, string add)>() {
("some value", specificString),
("some other value", anotherSpecificString),
//TODO: Add more pairs here
};
then you can put it as a simple loop:
foreach (var pair in m_ToAdd)
if (somestring.Contains(pair.find))
result.add(pair.add);
Answers:
Q1. Is the (existing) pattern okay as it is?
A1. It can be tolerated if you are not going to add / remove if
s and if you have few if
s
Q2. Where is the 'breaking point' - what I mean, how many if
.. checks are okay before it is better to refactor?
A2. My rule of thumb is 4-5 if
s.
Q3. What other refactors would be a good match for this pattern?
A3. Model extraction: you have data (here it's List<(string find, syting add)>
) and logics ( foreach
loop) separated.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.