Constructor vs getter,setter

Posted on 2011-03-14
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
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.


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 167 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 27

Assisted Solution

dpearson earned 167 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 166 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

Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

Question has a verified solution.

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

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Suggested Courses

732 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