java 构造函数中有很多参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7962398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:14:13  来源:igfitidea点击:

Having lots of parameters in a constructor

javainheritanceparametersconstructor

提问by KyelJmD

Is it wrong to have a lot of parameters inside a constructor? Like 10 to 15 parameters? Because I was designing a class where a constructor will have lots of parameters, for example, a Personclass.

构造函数中有很多参数是错误的吗?像 10 到 15 个参数?因为我正在设计一个类,其中构造函数将有很多参数,例如一个Person类。

My example person class has 6 parameters in its constructor:

我的示例人员类在其构造函数中有 6 个参数:

public class Person {
    private String fName;
    private String lName;
    private String mInitial;
    private int age;
    private String contactNumber;
    private String emailAddress;

    public Person(String fName, String lName, String mInitial, int age, String contactNumber, String emailAddress) {
       //insert rest of code here 
    }
}

Is that wrong? Creating lots of parameters for a constructor?

错了吗?为构造函数创建大量参数?

Then I am planning to create a class named Employee, then extending it to person class, then it will have a long constructor as well.

然后我打算创建一个名为 的类Employee,然后将它扩展到 person 类,然后它也会有一个很长的构造函数。

The thing that worries me about is the practice, is this good or what? Any other suggestions?

我担心的是练习,这是好还是什么?还有其他建议吗?

采纳答案by necromancer

  1. In general, if you find yourself have too many parameters, that means you don't have enough low-level classes. In your case, you could have a class Name { /* fname, lname, initial, */ }and perhaps a class Contact { /* email, phone */ }

  2. When you extend your class, have the constructor take the base as one parameter, and then add the new extra parameters. (You probably mean Employee will extend Person, rather than vice versa, so public Employee (Person person, Company company, String employeeId) { super(person); this.company = company; this.employeeId = employeeId; }

  1. 一般来说,如果你发现自己有太多的参数,那就意味着你没有足够的低级类。在你的情况下,你可以有一个class Name { /* fname, lname, initial, */ },也许一个class Contact { /* email, phone */ }

  2. 当你扩展你的类时,让构造函数将基作为一个参数,然后添加新的额外参数。(您可能是说 Employee 会扩展 Person,而不是相反,所以public Employee (Person person, Company company, String employeeId) { super(person); this.company = company; this.employeeId = employeeId; }

Good question!

好问题!

回答by Prince John Wesley

Instead of using telescoping constructor pattern, use builder pattern

不要使用伸缩构造函数模式,而是使用构建器模式

public class Person {
    private final String fName;
    private final String lName;
    private final String mInitial;
    private final int age;
    private final String contactNumber;
    private final String emailAddress;

    public Person(PersonBuilder builder) {
       //insert rest of code here 
       fName = builder.fName;
       ...
    }

    public static class PersonBuilder {
        private String fName;
        private String lName;
        private String mInitial;
        private int age;
        private String contactNumber;
        private String emailAddress;
        // setter methods
        public PersonBuilder setFirstName(String name) {
             fName = name;
             return this;
        }
        ...
        // build method
        public Person build() {
            return new Person(this);
        }

    }
}

...

...

Person p = new PersonBuilder()
              .setFirstName("")
              // set all the setter methods
              .build();

回答by Sahil Muthoo

You could decompose Personinto Nameand Contact.

你可以分解PersonNameContact

public class ComposedPerson {
    private Name name;
    private int age;
    private Contact contact;

    public ComposedPerson(Name name, int age, Contact contact) {
        this.name = name;
        this.age = age;
        this.contact = contact;
    }

    public static void main(String... args) {
        Name name = new Name("John");
        Contact contact = new Contact("12345", "[email protected]");
        ComposedPerson person = new ComposedPerson(name, 45, contact);
   }

Sample Name. See how I use a telescoping constructor to allow for optional arguments.

样品Name。看看我如何使用伸缩构造函数来允许可选参数。

public class Name {
    private String fName;
    private String lName;
    private String mInitial;

    public Name(String fName) {
        this(fName, null, null);
    }

    public Name(String fName, String lName) {
        this(fName, lName, null);
    }

    public Name(String fName, String lName, String mInitial) {
        this.fName = fName;
        this.lName = lName;
        this.mInitial = mInitial;
    }
} 

回答by Kit Ho

Yes it is not good to have many parameters in any kind of functions. Maximum parameters should be around 7, according to a book named Code Complete 2.

是的,在任何类型的函数中都有很多参数都不好。根据一本名为 Code Complete 2 的书,最大参数应该在 7 左右。

It is because it will decrease the code readabilityand maintainabilityand usability. Imagine other developers working on the same project, how to follow your code?

这是因为它会降低代码的可读性可维护性可用性。想象一下在同一个项目上工作的其他开发人员,如何遵循您的代码?

There are lots of different ways to handle this, factory pattern, for example. It depends on how you design your application.

有很多不同的方法来处理这个问题,例如工厂模式。这取决于您如何设计应用程序。

But in your code, I think it is ok that the no. of parameters is still acceptable (6 parameters)

但是在你的代码中,我认为没有。参数还是可以接受的(6个参数)

If your object require so many parameters to instantiate, then you need to rethink how you design your code. For example, can some of the attributes wrap into a separate class? can some of the attribute not necessary pass as a parameter? i.e., get the value from the other class. etc...

如果您的对象需要如此多的参数来实例化,那么您需要重新考虑如何设计您的代码。例如,是否可以将某些属性包装到一个单独的类中?某些不需要的属性可以作为参数传递吗?即,从另一个类中获取值。等等...