aspose 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 Groovy Fundamentals video training course this week in the Groovy forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "constructor misuse ?" Watch "constructor misuse ?" New topic

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

Joined: Sep 20, 2010
Posts: 3791

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.
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 42643
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?
I agree. Here's the link:
subject: constructor misuse ?