代码重构-2 简单不变的 if else 用字典代替

 

原代码

private string GetExDesc(string lotteryCode)
{
string exDesc = "抽奖";
if (lotteryCode.ToLower() == "zajindan")
{
exDesc = "砸蛋";
}
else if (lotteryCode.ToLower() == "guaguaka")
{
exDesc = "刮卡";
}

return exDesc;
}

很简单不变的if..else..可以用 字典代替,扩充也方便

重构后:

 

private static readonly Dictionary<string,string > MarketingCodeDescDict=new Dictionary<string,string> ()
{
{"zajindan","砸蛋"},
{"guaguaka","刮卡"},
{"choujiang","抽奖"}
};

/// <summary>
/// 获取抽奖操作的动作描述:抽奖/砸蛋/刮卡
/// </summary>
/// <param name="lotteryCode"></param>
/// <returns></returns>
private static string GetMarketingCodeDesc(string lotteryCode)
{
lotteryCode = lotteryCode.ToLower();
if (MarketingCodeDescDict.ContainsKey(lotteryCode))
{
return MarketingCodeDescDict[lotteryCode];
}
throw new Exception(string.Format( "lotteryCode:{0} is   invalid",lotteryCode));

}

 

posted @ 2016-01-05 11:12  zslm___  阅读(766)  评论(0编辑  收藏  举报