am new here and i want to know what would be better passing information to a method or a constructor
String value = Work(name: name, job: job).add();
or
String value = Work().add(name: name, job: job);
CodePudding user response:
When passing arguments to constructer it means that you're going to use the passed variable in the whole class multiple time. By passing it as method, you're using it once for calculation or expecting result
For Example, Imagine that you're making a calculator. You don't pass the numbers into constructor! you pass it as method
Caclulator.add(int x,inty) // Just calculate once
In the other hand, Imagine car class and it's need to define the car. in this case you pass the argument in constructor
var tmp = Car(wheelsNumber: 4,color: Colors.green) // We define the Car shape
tmp.moveForward(speed: 30) // Call method to move forward with 30Kmh
tmp.moveForward(speed: 10) // Change the speed
In the example we change the speed calculation and it's not logical to pass the speed parameter in constructor
CodePudding user response:
It depends on the use case of your Work
class.
If it can not exist without values, for example, if class members depend on them, you should assign them as early as possible i.e. in the constructor to make it practically impossible to forget them.
If that didn't help, can you explain what the class/method does?