Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium


Constructor vs getter,setter

Posted on 2011-03-14
Medium Priority
Last Modified: 2012-05-11
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 .

Question by:FranklinRaj22
LVL 47

Expert Comment

ID: 35130895
LVL 47

Expert Comment

ID: 35130968
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.
LVL 47

Expert Comment

ID: 35130989
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!


Author Comment

ID: 35131373
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 .
LVL 47

Accepted Solution

for_yan earned 668 total points
ID: 35131546
Well, frankly I would confess that I many times in my experience ended up with these chains and had
to pass references this way, modifying the code in many places after I had some additional request.
 That was probably the result of the fact that I was not very smart, and also,
that I'm not usually writing
big programs and my customers are sitting right next to me, so when after some time of my work
they tell me to change everything, I have to accommodate them.
In general if you can pre-view your application from before, you probably want to identify
those variables which you'll need across your application in many classes or classes removed far away from each other
in the calling chain and you will want to have a kind
of general class where you want to keep all of them and have reference to that class passed to all the rest of your classes,
so that majority of your generally used values will be available that way, and you'll never
need to modify or add setters to the whole chain when you need it.
Don't know maybe someone will give us some more formal  recommendation, but that is my as I beleive common
sense attitude. Unfortunately many things depend on that situation of whether you can have good formal
specifications and then formal design in your work and strictly stick to it, or you don't have this kind of environemnt.

LVL 28

Assisted Solution

dpearson earned 668 total points
ID: 35135299
If you asked this question 10 years ago there was a lot of debate on the way to do this.  Today I'd say that has changed to say that you should definitely use a constructor.

What's more you should try hard to make the members of the class "final" - that is to the make the "immutable", guaranteeing it will never change.

The reason to do this is fairly subtle but it's because these types of objects work hugely better in multi-threaded systems.  10 years ago those weren't that common.  Today my laptop has 4 cores and in 2-3 years 16-core systems will be routine.  So multi-threaded support is no longer an after thought.

To answer the question of how to pass data from A to D via B and C, you should be exposing the data that you need to pass as a separate class (if it's more than one or two values).

So the pattern to pass x,y,z from A to D becomes:
class A {
      T getDataDNeeds() { return new T(x,y,z) ; }

   class B {
      private A myA ;
      T getDataDNeeds() { return myA.getDataDNeeds() : }

   class C {
      private B myB ;
      T getDataDNeeds() { return myB.getDataDNeeds() : }     
   class D {
      private C myC ;

      public void getMyStuff() { 
          T myT = myC.getDataDNeeds() ;
          int x = T.getX() :
          int y = T.getY() ;
          int z = T.getZ() :

public class T {
     private final int myX ;
     private final int myY ;
     private final int myZ ;
     public T(int x,y,z)  {
         myX = x ; myY = y; myZ = z ;
     int getX() { return myX ; }

Open in new window

Notice how B and C have no idea what they're passing along.  If you later need more data from A, you can extend T and you won't have to modify B and C at all.

LVL 19

Assisted Solution

by:Jim Cakalic
Jim Cakalic earned 664 total points
ID: 35223528
For me, constructor v. setter is more a matter of aesthetics than strict rule. I agree that the best case is when objects are instantiated with all required knowledge. Whether the required fields are then immutable is a specific design question. A long list of constructor parameters can be a visual clue that perhaps the class has become too large, knows too much, has too many responsibilities, too many collaborators. Or not. It could be that this is an entity (e.g., Employee) that just happens to have a lot of relationships. The aesthetics comes in to play, for me, when I look at the code. If I don't like the way it looks say with long constructor arg lists then I might add/use the setters if this doesn't violate some other sense of correctness in the design. I have even, on occasion, when the object was just a dumb data holder, written it essentially like a struct with all public fields, no methods and only a no-arg constructor. These don't always survive later refactorings.

Agree with dpearson regarding passing parameters. The refactoring for this is Introduce Parameter Object. In your scenario, if all the values needed as parameters are contained in class A but you don't want to pass A through the call chain you might consider initially defining an interface with getters for the parameters. A can implement the interface so that B, C and D do not know A directly. The side benefit (possibly) is that the parameter object appears to be immutable - assuming that's a good thing. If your requirements/design changes then you could have multiple implementations of the interface without needing to change the classes that depend on it.


Featured Post

Become an Android App Developer

Ready to kick start your career in 2018? Learn how to build an Android app in January’s Course of the Month and open the door to new opportunities.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
The viewer will learn how to implement Singleton Design Pattern in Java.
Suggested Courses
Course of the Month13 days, 21 hours left to enroll

581 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question