Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Best Practice new vs .create() [duplicate]

Well, i have a very conceptual question. A lot of things look like fabrics, where i'm not sure where the great benefit is. As example

public class MyObject {
public MyObject() {

}
public static MyObject create() {
    return new MyObject();
}

public void doSomething(){
    // some code...
};

}

The only benefits from my point of view is a bid less to code. In my opinion, no impact on performance happens. Are there other benefits?

MyObject myobject = new MyObject();

or

MyObjecct myobject = MyObject.create();

Thanks

like image 390
MemLeak Avatar asked Jun 26 '13 13:06

MemLeak


Video Answer


1 Answers

You are correct in that there is no significant performance difference; and the reasons for using this form are primarily about readability of the code.

In general if you use the static create function you would declare the constructor private thus ensuring your users can ONLY create objects with the static function

In general I don't think the static create adds much to code, ad for ordinary everyday objects a new is probably clearer and more direct.

However there are some cases that I think the static constructor is useful:

  1. For construction of large complicated objects, especially objects involving a lot of complexity in initialisation - often a simple constructor misleads library users into assuming the construction task is fast and easy.
  2. If you have multiple constructors with ambiguous parameters you can use the static function name to make it more readable, for example you might have createFromFile(String FileName) and createFromJSONEncoding(String Data)
  3. You want to control if a new object is ACTUALLY created - for example if this is a read-only resource you might be keeping a buffer of the resources already open and if the library user requests the same resource twice you can simply give them an already cached copy (as opposed to making a new duplicate copy)
like image 125
Elemental Avatar answered Sep 21 '22 20:09

Elemental