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

6

5

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

Ferrous answered 26/6, 2013 at 13:38 Comment(2)
create should be static in your example.Fop
Also take a look here: #3169872Fop
K
5

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)
Karmen answered 26/6, 2013 at 13:50 Comment(0)
T
2

Joshua Bloch addresses this concern in Effective Java, Chapter 2, Item 1: Consider static factory methods instead of constructors; here are a few highlights:

  • "One advantage of static factory methods is that, unlike constructors, they have names." -- you can't have two different constructors that take an int argument, but you can have two static factory methods called createWithAge(int age) and createWithHeight(int height)
  • "A second advantage of static factory methods is that, unlike constructors, they are not required to create a new object each time they’re invoked."
  • "A third advantage of static factory methods is that, unlike constructors, they can return an object of any subtype of their return type."

As you see, the concern is hardly related to performance (except for reusing cached instances), but mainly to object oriented design.

DISCLAIMER: Oops, I just saw the same answer (far better explained) already being posted for a different question: https://mcmap.net/q/238005/-when-to-use-a-constructor-and-when-to-use-getinstance-method-static-factory-methods. My bad...

Troutman answered 26/6, 2013 at 13:52 Comment(0)
K
1

The case I see where you might need to use create:

You have to control creation of every instance of your class. For example, you count number of objects created or link them somehow and if number of instances reached your desired maximum throw exception.

Also factory pattern might be interesting to read about.

If you're not sure, just create via new

And if you choose to go with create you'd probably want to make your constructor private

Klepht answered 26/6, 2013 at 13:43 Comment(4)
A Constructor can also throw an exception.Configurationism
sure, I meant that it checks some constraints and throws exceptionKlepht
How is that different from what you can do in a constructor?Configurationism
you can do whatever you want, it just keeps code cleaner and mroe readableKlepht
C
1

There is no answer to this question.

The fact is that both patterns are legitimate ways to construct objects that are applicable to particular situations.

Static factory methods are important in situations where instance control is very important, such as in systems that maintain object caches or pools.

The new operator is apt for its simplicity and is rather important for classes that are designed for inheritance.

You are asking what is the best practice. The answer is that the best practice depends on your goals and, as always for questions of this sort, the best practice is that which makes smart use of available tools to reach a scalable and maintainable solution.

I suggest that this question be closed.

Chimere answered 26/6, 2013 at 13:48 Comment(2)
-1 You imply there is an answer 'that the best practice depends on your goals', refuse to explain that answer - and then tell the asker it was a bad question. If you feel this way you should just vote the question down if you don't have the rep to vote to close.Karmen
@Elemental: Ok, so ... what part of "static factory methods are important for instance control" ... and ... "new is apt for classes designed for inheritance" doesn't sound like an explanation to you?Chimere
P
0

It is a (simplistic) Factory Pattern. Please check the applicability section of the Wikipedia entry to see where it is used.

Piliform answered 26/6, 2013 at 13:43 Comment(0)
C
0

Now when you don't wan't any other class to create your class' object then you make you class constructor private:

private MyObject()

now any class wanting to create your class object will have to do this :

MyObjecct myobject = MyObject.create();

Because now doing this inside some other class MyObject myobject = new MyObject(); will cause compiler error.

Cantharides answered 26/6, 2013 at 13:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.