OOP object constructor arguments

When do I need to pass arguments to the constructor of an object? What criteria do you use to pass them to the constructor instead of arguments in object methods?

+4
source share
4 answers

Pass things to the constructor that are immutable properties of the object. Whenever possible, make all the properties of an object immutable. In full, this allows you to completely destroy the object.

The immutable properties assigned during construction avoid various race conditions (especially in multi-threaded environments) and help to ensure that the object is always consistent, which eliminates the possibility of many errors. By forcing properties to be defined during construction, you avoid extensive error checking code. As soon as the entire object can be immutable, there is scope for exchanging equivalent objects, which improves memory performance.

If the parameter is not an immutable property of the object, then its purpose in the constructor is just a convenience. In general, it should be appointed by the installer to reduce code complexity (since a setter is required anyway). If the constructor is called very often, then the convenience of the parameter may be worth this additional complexity.

+3
source

When my object is very simple (1 or two attributes), I can provide a constructor with these arguments.

But most of the time, the default constructor and I set my attributes with setters.

+1
source

You usually pass arguments to the class constructor when creating an instance of the class with the new keyword (this may vary depending on the language).

For example (select C / Java / C # style here)

 MyClass class = new MyClass(arg1, arg2, arg3); 

When re-reading your question, I tend to use constructor arguments for absolutely necessary resources. Thus, you know that your object must have certain properties or available resources.

0
source

Basically, you want to initialize all the basic building blocks of an object in the constructor. But sometimes an object contains many elements, so it is too difficult to create an argument list for the constructor. I follow this guide: if the argument list for the constructor is more than 5 elements, the initialization of the new object is divided into constructor arguments and set methods.

0
source

All Articles