gpt4 book ai didi

c# - 反DRY模式

转载 作者:太空狗 更新时间:2023-10-29 23:53:46 25 4
gpt4 key购买 nike

这组代码我写过,感觉挺差的在质量上。如您所见,在四个 case 语句的每一个中我最终重复了很多相同的代码,除了每种情况都有一些变化。变化的项目; session 名称、网格名称和 ManagerContext 组名称。任何人都可以把这些乱七八糟的代码和告诉我更好的方法吗?

private void LoadGroup(string option)
{
switch (option.ToUpper())
{
case "ALPHA":
VList<T> alphaList = FetchInformation(
ManagerContext.Current.Group1);

if (Session["alphaGroup"] != null)
{
List<T> tempList = (List<T>)Session["alphaGroup"];
alphaList.AddRange(tempList);
}
uxAlphaGrid.DataSource = alphaList;
uxAlphaGrid.DataBind();
break;
case "BRAVO":
VList<T> bravoList = FetchInformation(
ManagerContext.Current.Group2);

if (Session["bravoGroup"] != null)
{
List<T> tempList = (List<T>)Session["bravoGroup"];
bravoList.AddRange(tempList);
}
uxBravoGrid.DataSource = bravoList;
uxBravoGrid.DataBind();
break;
case "CHARLIE":
VList<T> charlieList = FetchInformation(
ManagerContext.Current.Group3);

if (Session["charlieGroup"] != null)
{
List<T> tempList = (List<T>)Session["charlieGroup"];
charlieList.AddRange(tempList);
}
uxCharlieGrid.DataSource = charlieList;
uxCharlieGrid.DataBind();
break;
case "DELTA":
VList<T> deltaList = FetchInformation(
ManagerContext.Current.Group4);

if (Session["deltaGroup"] != null)
{
List<T> tempList = (List<T>)Session["deltaGroup"];
deltaList.AddRange(tempList);
}
uxDeltaGrid.DataSource = deltaList;
uxDeltaGrid.DataBind();
break;
default:
break;
}
}

最佳答案

您应该能够将案例的各个部分提取到参数化辅助函数中:

function helper(grp, grpname, dg) {
VList<T> theList = FetchInformation(grp);
if (Session[grpname] != null)
{
List<T> tempList = (List<T>)Session[grpname];
theList.AddRange(tempList);
}
dg.DataSource = theList;
dg.DataBind();
}

private void LoadGroup(string option)
{
switch (option.ToUpper())
{
case "ALPHA":
helper(ManagerContext.Current.Group1, "alphaGroup", uxAlphaGrid);
break;
case "BRAVO":
helper(ManagerContext.Current.Group2, "bravoGroup", uxBravoGrid);
break;
case "CHARLIE":
helper(ManagerContext.Current.Group3, "charlieGroup", uxCharlieGrid);
break;
case "DELTA":
helper(ManagerContext.Current.Group4, "deltaGroup", uxDeltaGrid);
break;
default:
break;
}
}

这是一种选择,我敢肯定还有进一步的重构。

对于更深入的重构,我会考虑使用一组选项对象、可能的委托(delegate)或类似对象的表驱动。其工作方式是该选项将成为一个对象而不是一个字符串,并且该选项将具有配置它的属性和调用适当委托(delegate)的方法。这实际上取决于您要维护的抽象级别。有时从常规控件继承并在子类中提供配置信息以便它们知道如何加载自己是值得的。

这里没有足够的空间来真正深入到重构的深度。

关于c# - 反DRY模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1947951/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com