Solved

Constructor vs getter,setter

Posted on 2011-03-14
7
908 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
Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

 

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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
maven project error 5 54
Error trying to install RTMT Win7 5 59
even odd program using while loop 3 40
web application structure 18 76
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
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…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This video teaches viewers about errors in exception handling.

816 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

8 Experts available now in Live!

Get 1:1 Help Now