Constructor with all class properties or default constructor with setters?

前端 未结 9 1905
无人及你
无人及你 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:50

    You mention it in your post, but I think this is an important point that deserves more attention: unless every input parameter is a different type, the big problem with huge constructors is that it's very easy to transpose a couple of variables. The compiler is an unreliable safety net -- it will catch some mistakes, but the ones that slip through are going to be much more difficult to identify and debug. Especially because the input list for a huge constructor is quite opaque unless you've got the API open in another window.

    Getters and setters are vastly easier to debug, especially if you institute safeguards that throw a runtime exception if the object isn't properly populated. And I'm a huge fan of "easy to debug."

    Prior to this thread I'd never heard of the Builder pattern Rob mentions. Never used it myself (obviously), but it's damned intriguing.

    0 讨论(0)
  • 2020-12-24 14:51

    There are other aspects as well. If you want to be able to certain things with your class at design time rather than just at runtime, for example adding your class as an object in the Object Palette (this is Java using Netbeans) you need to provide a no-argument constructor in order to be able to do so.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题