File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes constructor misuse ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Head First Android this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "constructor misuse ?" Watch "constructor misuse ?" New topic
Author

constructor misuse ?

nimo frey
Ranch Hand

Joined: Jun 28, 2008
Posts: 580
Is it good design to have a constructor with parameters being not within the class of the constructor?

For example:



So you see I have two properties within my constructor only for internal calculation to represent the property newDate. Is that totally okay or should I do that in a method which returns a new Instance of User instead of a constructor?:




Which way is better?
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3882
    
  18

It completely depends.

There's nothing wrong with using a constructor that way. However, a factory method has the advantage of being able to create subclasses of the return type, and it isn't even required to return an instance at all.

I generally use factory methods for my "value" classes, immutable classes that model some sort of value (examples from the API are Integer, String, etc), so I have the option to add value caching to my class later on, even if I usually don't. With most classes though, I usually just make a public constructor.

If you can foresee that you want to provide clients with subclasses of your User class later on, you should use factory methods. Otherwise I would just go with the constructor.

Wait what others have to say, they may have much more insight in this matter than I do.


The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 43282
    
  32
I presume when you wrote an int followed by a dot . you were trying to see whether the rest of us are awake.
nimo frey
Ranch Hand

Joined: Jun 28, 2008
Posts: 580
oh yes.

The point of the question is: Is it okay to design something like that? Would it be really better to use something like CDI (Context and Dependency Injection) with Factory injection?
 
Consider Paul's rocket mass heater.
 
subject: constructor misuse ?
 
It's not a secret anymore!