如何减少构造函数中过多的参数[已关闭]

问题描述 投票:0回答:4

我在命令服务类的构造函数中使用了 9 个参数,但 sonarqube 显示参数太多的错误。谁能提出解决方案或设计模式来解决这个问题?

public CustomerCommandService(A a, B b, C c, D d, E e, F f, G g, H h, I i){
//some code here
}
c# design-patterns .net-core sonarqube coding-style
4个回答
2
投票

这不是错误,而是警告。无论如何,您应该避免使用尽可能多的参数。尝试将您的服务分解为一些子服务。另外,正如 Div 所说,您可以使用 builder 模式


1
投票

您是否考虑过使用结构来包含不同的参数,然后将此结构传递给构造函数

public struct CustomerParams
{
    A a;
    B b;
    ...
}
public CustomerCommandService(CustomerParams cp)
{

}

0
投票

您可以使用结构体、类对象或元组来实现您想要的。

Struct 和 Class 几乎相同,只是关键字会改变。样品:

struct Pack
{
     int a,b;
     float c,d;
     String e;
}

public static Main()
{
     Pack pack = new Pack();
     pack.a=10;
     pack.b=30;
     ...
     CustomerCommandService ccs = new CustomerCommandService(pack);
}

public CustomerCommandService(Pack pack){
      //some code here
}

元组样本:

public static Main()
{
     var pack = Tuple.Create(1, 2, 10.4, 30.5, "Steve");
     CustomerCommandService ccs = new CustomerCommandService(pack);
}

public CustomerCommandService(Tuple<int,int,float,float,string> pack){
      //some code here
}

-1
投票

当一个函数似乎需要两个或三个以上的参数时,很可能其中一些参数 这些论点应该被包装到它们自己的一个类中。例如,考虑 以下两个声明之间的区别:

Circle makeCircle(double x, double y, double radius);
Circle makeCircle(Point center, double radius);

希望这篇帖子对您有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.