mercredi 10 juin 2015

How to refactor repeated code using reflection

So I have this large switch statement which is essentially the same code repeated multiple times where the only thing changing is the cast to a specific class. I've been trying to figure out a way to refactor it using reflection so I only have to write it once.

switch(provider)
{
               case SocialNetworks.Linkedin:
                    {
                        List<Linkedin> profiles = await MobileService.GetTable<Linkedin>().Where(p => p.uuid == (obj as Linkedin).uuid).ToListAsync();
                        if (profiles.Count == 0)
                        {
                            await MobileService.GetTable<Linkedin>().InsertAsync(obj as Linkedin);
                        }
                        break;
                    }
                case SocialNetworks.Facebook:
                    {
                        List<Facebook> profiles = await MobileService.GetTable<Facebook>().Where(p => p.uuid == (obj as Facebook).uuid).ToListAsync();
                        if (profiles.Count == 0)
                        {
                            await MobileService.GetTable<Facebook>().InsertAsync(obj as Facebook);
                        }
                        break;
                    }
                case SocialNetworks.Twitter:
                    {
                        List<Twitter> profiles = await MobileService.GetTable<Twitter>().Where(p => p.uuid == (obj as Twitter).uuid).ToListAsync();
                        if (profiles.Count == 0)
                        {
                            await MobileService.GetTable<Twitter>().InsertAsync(obj as Twitter);
                        }
                        break;
                    }
}

Note that here obj is of type Object and MobileService is of type MobileServiceClient which is part of the Windows Azure Mobile Service library.





Aucun commentaire:

Enregistrer un commentaire