Tôi có 3 chức năng nơi sự khác biệt duy nhất ở là các giá trị tôi chỉ ra với bình luậnLàm thế nào để cấu trúc lại các chức năng này có một dòng khác biệt
//-- point of difference
Phần lớn các chức năng là như nhau trên tất cả ba. Các "DRY" yếu tố là ám ảnh giấc ngủ của tôi :). Tôi đã tự hỏi; những thứ này có thể được hợp nhất dễ dàng và dễ đọc không?
Tôi đã có những tình huống như thế này trước đây và tôi hy vọng sẽ tìm hiểu điều gì đó ở đây.
private string RenderRequestType(string render, NameValueCollection nvp, string prefix, string regexWild, string suffix)
{
string regex = prefix + regexWild + suffix;
MatchCollection matches = Regex.Matches(render, regex);
foreach (Match match in matches)
{
foreach (Capture capture in match.Captures)
{
string name = capture.Value.Replace(prefix, "", StringComparison.CurrentCultureIgnoreCase).Replace(suffix, "", StringComparison.CurrentCultureIgnoreCase);
//-- point of difference
string value = nvp[name];
render = render.Replace(capture.Value, value);
}
}
return render;
}
private string RenderSessionType(string render, HttpContext httpContext, string prefix, string regexWild, string suffix)
{
string regex = prefix + regexWild + suffix;
MatchCollection matches = Regex.Matches(render, regex);
foreach (Match match in matches)
{
foreach (Capture capture in match.Captures)
{
string name = capture.Value.Replace(prefix, "", StringComparison.CurrentCultureIgnoreCase).Replace(suffix, "", StringComparison.CurrentCultureIgnoreCase);
//-- point of difference
object session = httpContext.Session[name];
string value = (session != null ? session.ToString() : "");
render = render.Replace(capture.Value, value);
}
}
return render;
}
private string RenderCookieType(string render, HttpContext httpContext, string prefix, string regexWild, string suffix)
{
string regex = prefix + regexWild + suffix;
MatchCollection matches = Regex.Matches(render, regex);
foreach (Match match in matches)
{
foreach (Capture capture in match.Captures)
{
string name = capture.Value.Replace(prefix, "", StringComparison.CurrentCultureIgnoreCase).Replace(suffix, "", StringComparison.CurrentCultureIgnoreCase);
//-- point of difference
HttpCookie cookie = httpContext.Request.Cookies[name];
string value = (cookie != null ? cookie.Value : "");
render = render.Replace(capture.Value, value);
}
}
return render;
}
Câu hỏi này rất dễ dàng, nhưng tôi suy nghĩ khá hữu ích cho nhiều người mới bắt đầu. +1 –