Lum*_*ums 2 .net c# oop design-patterns
我们假设我有以下课程
public static class ClassA
{
public static Type2 B { get; set; }
public static Type3 C { get; set; }
public static Type4 D { get; set; }
public static string Method(Type1 a, Type2 b, Type3 c, Type4 d)
{
//do smth
}
public static string Method(Type1 a, Type2 b, Type3 c)
{
Type4 d = D ?? defaultValue4;
return Method(a, b, c, d);
}
public static string Method(Type1 a, Type2 b, Type4 d)
{
Type3 c = C ?? defaultValue3;
return Method(a, b, c, d);
}
public static string Method(Type1 a, Type3 c, Type4 d)
{
Type2 b = B ?? defaultValue2;
return Method(a, b, c, d);
}
public static string Method(Type1 a, Type2 b)
{
Type3 c = C ?? defaultValue3;
Type4 d = D ?? defaultValue4;
return Method(a, b, c, d);
}
public static string Method(Type1 a, Type4 d)
{
Type2 b = B ?? defaultValue2;
Type3 c = C ?? defaultValue3;
return Method(a, b, c, d);
}
public static string Method(Type1 a, Type3 c)
{
Type2 b = B ?? defaultValue2;
Type4 d = D ?? defaultValue4;
return Method(a, b, c, d);
}
public static string Method(Type1 a)
{
Type2 b = B ?? defaultValue2;
Type3 c = C ?? defaultValue3;
Type4 d = D ?? defaultValue4;
return Method(a, b, c, d);
}
}
Run Code Online (Sandbox Code Playgroud)
其中我必须使用4个参数的组合,其中A始终是必需的,而其他参数是按参数的优先级顺序,否则来自属性,如果没有设置属性或没有参数从其默认值传递.我需要在没有公开代码的情况下重新设计它,所以这些行
Type2 b = B ?? defaultValue2;
Type3 c = C ?? defaultValue3;
Type4 d = D ?? defaultValue4;
Run Code Online (Sandbox Code Playgroud)
一次只写一次.这可能吗?
以上都不是.创建一个接受表示参数的对象的方法:
public static string Method(MethodArgs args)
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
这MethodArgs可以按照你喜欢的方式进行组织,或者与这个类一起或者作为一个内部类,或者甚至在一个完全独立的DTO命名空间和诸如此类的东西中.
在MethodArgs类中,您可以验证参数,执行您喜欢的任何逻辑,在参数本身上强制执行业务规则,公开功能以手动验证逻辑等.然后在Method()您将验证args它们处于某种有效状态并继续进行在那个州.
看起来你在这里展示的唯一逻辑是提供默认值,它可以很容易地封装在构造函数中MethodArgs.