From a design perspective, when is it better to remove method arguments and, instead, use constructor arguments where the methods can use class variables that have been initialized to the constructor arguments?
Use constructor arguments when Object of the Class cannot be considered fully initialized without those parameters. For example: If you are creating Employee class and you want that each instance of Employee must have name, then, you should use name as parameter in constructor. Another example, is you cannot create File class without specifying name of the file to be opened.
Parameters that are only relevant in the context of a method should be passed as method parameter. Example, can be when you are adding a new item to a List class. This may internally update the state of the Object, but thats how this class works - it has internal data structure to maintain list, and methods are meant to manipulate those state.
Sometimes underlying frameworks may expect you to initialize state using setter methods. This is typically a case when using ORMs like Hibernate or when using POJO Beans such as Model objects in web forms in MVC frameworks (Spring MVC for example). In those cases, the classes typically represent Value Object, and it is general practice to not to pass parameters in the Constructor as frameworks instantiate the object using default no-arg constuctor
When using Dependency Injection frameworks, you will find that dependencies can be injected using Constructor or by using setter methods. In such cases, you should aim for using Constructor params for mandatory dependencies, and use setter for optional dependencies - though it is not necessary to do so. You can think of it as a guideline.
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