About designers

I have a question about designers. I think that all constructors are just our convenience instead of setter methods, right? Thus, for an object, properties that you consider important (for example, required fields in a web form) are passed as parameters to the constructor.

Is there any criterion for these numerous numbers of parameters to be passed to the constructor? Please clarify these points, as well as any questions about the designers.

Edit : sorry for the way I asked the question. Yes, we create an object with a constructor, and we assign values ​​with setters, but my question is about comparing the default constructor with setters and the constructor with explicit parametrs.

+5
source share
7 answers

No, it's not just convenience instead of setters. In particular, the constructor will be called only once. Using constructor parameters, you can create immutable types that are assigned their values ​​during construction - this would not be possible with setters.

As a rule, it is not a good idea to have a huge number of parameters, be it a constructor or a regular method. If you find that you have many parameters, you may need to create a type that represents all the related ones - this type may have a bunch of getters / setters. For an example see ProcessStartInfo.

+11
source

I see it like this:

You pass the parameters in the constructor that are needed to create an object that is in the "valid" state.

: - , .

+10

, . .

Re. . , :

  • . TimePeriod

Factory pattern Builder . .

. . Java # , , , ( , ). ( ).

+4

. , .

, .

+3

, looong ( , ),

Builder

.

+2
0

, , , . , , , .. :

  • : , . , . , , Java, . ( ) ( ) , , . , , ; , Java, String ( ) StringBuilder StringBuffer ( ). String , , StringBuilder , . StringBuffer , , , ( : , ). , : ( ) , , , .

  • :. , ​​ Spring Guice, , . , spring , . spring (beans), , setter. spring init (PostConstruct). , , , . , Guice .

  • : , , - . , . , . , , .

  • For a new or to delegate: . When you go to a new object using the methods of the constructor or setter to fill in the fields, it is recommended to think about whether it might be needed someday that someone else will go through (write, create) here. This leads to the Factory design pattern , which is especially useful when developing tools and libraries.

0
source

All Articles