When should I pass arguments to the object's constructor? Which criteria do you use to pass them to the constructor instead of arguments in object's methods?
Pass things to the constructor that are immutable properties of the object. When possible, make all object properties immutable. Taken to its full extent, this allows the entire objet to be immutable.
Immutable properties, assigned at construction, avoid a variety of race conditions (particularly in multi-threaded environments) and helps ensure that the object is always consistent, eliminating the possibility of many kinds of errors. By forcing properties to be defined at construction, you avoid extensive error-checking code. Once the entire object can be immutable, there are opportunities for sharing equivalent objects, improving memory performance.
If a parameter is not an immutable property of the object, then assigning it in the constructor is merely a convenience. In general, it should be assigned with a setter to reduce code complexity (since the setter is required anyway). If the constructor is called very often, then the convenience of parameter may be worth this extra complexity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With