Constructor with all class properties or default constructor with setters?

前端 未结 9 1940
无人及你
无人及你 2020-12-24 14:03

Following are the two approaches:

  • constructor with all the class properties

Pros: I have to put an exact number of types of parameters so if I m

9条回答
  •  再見小時候
    2020-12-24 14:54

    I prefer taking constructor arguments, for the aforementioned immutability reasons. If that gives you a constructor that takes lots of arguments (say more than four or so), that's a code smell to me: some of those arguments should be bundled together into their own types.

    For example, if you have something like this:

    class Contact
    {
        public Contact(string firstName, string lastName, string phoneNumber,
            string street, string city, string state, int zipCode) { ... }
    }
    

    I'd refactor it to:

    class Contact
    {
        public Contact(Person person, PhoneNumber number, Address address) { ... }
    }
    
    class Person
    {
        public Person(string firstName, string lastName) { ... }
    }
    
    class PhoneNumber
    {
        public PhoneNumber(string digits) { ... }
    }
    
    class Address
    {
        public Address(string street, string city, string state, int zipCode) { ... }
    }
    

    Too-large classes are a really common design problem in OOP codebases.

提交回复
热议问题