This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

constructor misuse ?

 
nimo frey
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 5553
53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic