Solved

Constructor vs getter,setter

Posted on 2011-03-14
7
888 Views
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 .

0
Comment
Question by:FranklinRaj22
7 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 35130895
0
 
LVL 47

Expert Comment

by:for_yan
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.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35130989
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:FranklinRaj22
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 .
0
 
LVL 47

Accepted Solution

by:
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.


0
 
LVL 26

Assisted Solution

by:dpearson
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.

Doug
0
 
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.

Regards,
Jim
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
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 about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

757 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now