jeudi 19 janvier 2017

Avoding repitetive method implementation in C#

I'm having several class wherein i need to parse json object. I see the initial looping of this json object is pretty much same in all classes except sub methods.

For example, in Class1.cs

private static void FindObject(JToken token)
{
  switch (token.Type)
  {
      case JTokenType.Array:          
         JArray array = token as JArray;
         array.ForEach(a => FindObject(a));
         break;           
      case JTokenType.String:
         token.Replace(GetNewImgTag(token.ToString()));
         break;
      case JTokenType.Object:
         token.Children().ForEach(t => FindObject(t));
         break;
       case JTokenType.Property:
         JProperty prop = token as JProperty;

         if (prop.Value.Type == JTokenType.Array)
         {
             FindObject(prop.Value);
             return;
         }

         prop.Value = GetNewImgTag(prop.Value.ToString());
         break;
      default:
         throw new NotImplementedException(token.Type + " is not defined");
  }    
}

private static JToken GetNewImgTag(string text)
{
   ...
}

and Class 2.cs is

private static void FindObject(JToken token)
{
  switch (token.Type)
  {
      case JTokenType.Array:          
         JArray array = token as JArray;
         array.ForEach(a => FindObject(a));
         break;           
      case JTokenType.String:
         token.Replace(ReplaceLinks(token.ToString()));
         break;
      case JTokenType.Object:
         token.Children().ForEach(t => FindObject(t));
         break;
       case JTokenType.Property:
         JProperty prop = token as JProperty;

         if (prop.Value.Type == JTokenType.Array)
         {
             FindObject(prop.Value);
             return;
         }

         prop.Value = ReplaceLinks(prop.Value.ToString());
         break;
      default:
         throw new NotImplementedException(token.Type + " is not defined");
  }    
}

private static JToken ReplaceLinks(string text)
{
   ...
}

If you compare both classes, FindObject() is pretty much same except child method call. I need to implement this in several class. I'm trying to avoid this multiple duplicate method creation.

Can anyone suggest a better way to design this?

I saw similar post here but i'm unable to apply this delegates to my scenario.

Avoiding repetitive code in multiple similar methods (C#)

Aucun commentaire:

Enregistrer un commentaire