Link to home
Start Free TrialLog in
Avatar of FranklinRaj22
FranklinRaj22

asked on

Constructor vs getter,setter

I need to pass some values from one class A to another Class B that is being called in class A .
These values will be assigned to instance variable and used till teh life of the object of classB.Is it better to pass teh values through a constructor and assign it to Instance varibale declared insiste or is it betteer to use setter methods to assign it . Which one is a good programming practice and why ? or will it not matter .

Avatar of for_yan
for_yan
Flag of United States of America image

I usually put in the constructor something without which this class will not normall exist
or the object will not make sense.

Something which will have to be changed back and forth during the lifetime of the object
I set in the setter methods.
I still often end up adding getters and setters, which I didn't plan to have
in the very beginning as I then have a need to add more options which I didn't have in mind
in the beginning.

Of course if you write huge projects where you want to think all details over before
actually doing something then you'll probably do it differently.
Avatar of FranklinRaj22
FranklinRaj22

ASKER

Thanks Yan,

One more things is incase of Standalone Java application , if i need to transfer a value from Object Class A to Object of class D , A calls B , B calls C and C calls D ... so in this case the only way it to pass the values through all these classes right ... eventhough its not being used by B and C ??
Or is there a better way of handling these scenerios .
ASKER CERTIFIED SOLUTION
Avatar of for_yan
for_yan
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Avatar of dpearson
dpearson

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial