如何简化这个C#重复代码?

时间:2016-07-15 15:58:48

标签: c# .net generics refactoring

GetTranslation函数返回一个字符串。

ExistsHelper函数返回bool。

public static class ValidatorNotExistHelper
{
    public static string Country(int id)
    {
        return (!ExistsHelper.Country(id)) ? GetTranslation(ConfigTranslationCode.CountryNotExist) : string.Empty;
    }

    public static string State(int id)
    {
        return (!ExistsHelper.State(id)) ? ConfigTranslationCode.StateNotExist : string.Empty;
    }

    public static string City(int id)
    {
        return (!ExistsHelper.City(id)) ? ConfigTranslationCode.CityNotExist : string.Empty;
    }
}

您可能会注意到代码正在重复,条件语句。只有ExistsHelper处的功能和翻译消息不同。任何想法都将不胜感激。

编辑:

我可能还有Overloading,例如:

public static string City(int cityId, int stateId, int countryId)
{
     return (!ExistsHelper.City(cityId, stateId, countryId)) ? ConfigTranslationCode.CityNotExist : string.Empty;
}

public static string City(int cityId, int stateId)
{
     return (!ExistsHelper.City(cityId, stateId)) ? ConfigTranslationCode.CityNotExist : string.Empty;
}

2 个答案:

答案 0 :(得分:1)

您可以传入要用于存在检查的功能,如下所示:

$headers = "Organization: Sender Organization\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "X-Mailer: PHP". phpversion() ."\r\n" ;
$headers .= "Reply-To: Sender Name <sender@yahoo.com>\r\n";
$headers .= 'From: Sender Name <sender@yahoo.com>' . "\r\n";
$headers .= "Content-Type: text/plain; charset=utf-8\r\n"; 
$headers  .= "X-Priority: 1\r\n"; 
if (mail('sendTo@email.com', 'Subject', 'message', $headers)) {
   "Mail successful.";  
}else{
   "Mail failed.";
}   

这将成功地分解出一些共享逻辑,但代价是增加了一些复杂性。

如果你只有三种这样的方法,我很想留下它们。如果你有很多并且会增加更多,那么这种重构可能是值得的。

答案 1 :(得分:0)

你可以简化泛型,但它会让你的电话更复杂

如果您创建一个接口

public interface IExists
{
    int id{get;}
}

并确保所有Comparable类都实现它 即

public class City:IExists
然后你可以做

public static class ValidatorNotExistHelper<T>
      where T:IExists
{
    public static bool Exists(int id,IEnumerable<T> possibles)
    {
        return possibles.Any(p=>p.id == id);
    }
    public static string ValidateExists(int id,IEnumerable<T> possibles,string ErrorMessage)
    {
        return Exists(id,possibles) ? String.Empty : ErrorMessage;
    }
    //using lookup Enum
    public static bool Exists(ClassTypeEnum type, int id)
    {
        return Exists(id,Lookup.GetPossibles(type));
    }
    public static string ValidateExists(ClassTypeEnum type,int id)
    {
        return Exists(type,id) ? String.Empty : Lookup.GetError(type);
    }
}
//Enum based lookup
public static class Lookup<T>
      where T:IExists
[
     public IEnumerable<T> GetPossibles(ClassTypeEnum type)
     {
         switch(type)
         {
             case ClassTypeEnum.City:
                 return //source of Cities;
         }
     }
     public IEnumerable<T> GetError(ClassTypeEnum type)
     {
         switch(type)
         {
             case ClassTypeEnum.City:
                 return ConfigTranslationCode.CityNotExist;
         }
     }
?