• Post Reply Bookmark Topic Watch Topic
  • New Topic

Calling static factory method from constructor.  RSS feed

 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a class tha has a static method that parses a String into an instance of my class. I also want to write a constructor that takes a String as an argument, but I'm trying not to duplicate all the code. Currently what I'm doing is creating a dummy object that I parse from the String and then copying all the fields over to this object. It works, but I'm wondering if theres a better way. My current code resembles this.

[ March 14, 2006: Message edited by: Garrett Rowe ]
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Garret --

Turn it inside out. Move the guts of the static factory method into the constructor, then have the factory method just say "new Foo(String)."
 
Mandar Max
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you should move the code from your static method to the constructor and let the static method create a new object of type Foo.

For example:

[ March 14, 2006: Message edited by: Mandar ]
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Mandar,

Welcome to JavaRanch!

A bit of business: you may not have read our naming policy on the way in. It requires that you use a full, real (sounding) first and last name for your display name. A single name isn't enough. You can change your display name here. Thanks for your immediate attention.
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ernest Friedman-Hill:
Hi Garret --

Turn it inside out. Move the guts of the static factory method into the constructor, then have the factory method just say "new Foo(String)."


Thanks guys.. I guess since I wrote the method before I wrote the constructor, as the old saying goes, I couldn't see the forest for the trees.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!