简体   繁体   English

如何重构 string.contains 逻辑

[英]how to refactor string.contains logic

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... ... 100 行...

My questions are:我的问题是:

  1. 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?至少,我觉得这应该简化为一种接受可能值及其替换的方法,而不是重复的 if 逻辑?

  2. Where is the 'breaking point' - what I mean, how many if.. checks are okay before it is better to refactor? “断点”在哪里——我的意思是,在重构之前,有多少 if.. 检查没问题?

  3. 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. A1. It can be tolerated if you are not going to add / remove if s and if you have few if s如果您不打算添加/删除if s 并且您几乎没有if s,则可以容忍

  • Q2. Q2。 Where is the 'breaking point' - what I mean, how many if .. checks are okay before it is better to refactor? “断点”在哪里——我的意思是,在最好重构之前,有多少if .. 检查没问题?

  • A2. A2。 My rule of thumb is 4-5 if s.我的经验法则是 4-5 if s。

  • Q3. Q3。 What other refactors would be a good match for this pattern?还有哪些重构可以很好地匹配这种模式?

  • A3. A3. Model extraction: you have data (here it's List<(string find, syting add)> ) and logics ( foreach loop) separated.模型提取:您将数据(这里是List<(string find, syting add)> )和逻辑foreach循环)分开。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM