Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice to creating Objects in java

I'm reading the Effective Java book by Joshua Bloch. In the first chapter, he says to use factories instead of constructors and lists the advantages and disadvantages of this approach. As far as I see disadvantages are not closely related to to object construction.

Moreover, Bloch says that Java Bean style of construction has disadvantages as well. Source: http://www.javapractices.com/topic/TopicAction.do?Id=84

OK, so using constructors is not great, Java beans are not great, factories are nice, so you can do some cache lookups and avoid creating extra objects (depends on the situation, sometimes you dont want caching).

How am I supposed to create an object if I try to avoid constructors and java beans?

Am I missing a point? What is the best practice?

EDIT:

class Foo{
   private Foo(){}

   public Foo Create(){
      return new Foo();
   }

}
like image 746
DarthVader Avatar asked Mar 01 '26 22:03

DarthVader


1 Answers

Use constructors until you start to feel the disadvantages Bloch mentions. Then consider whether factories, dependency injection, or some other approach is better.

like image 133
Eric Wilson Avatar answered Mar 04 '26 11:03

Eric Wilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!