Using static factory methods instead of constructors

Asked

Viewed 90 times

6

I’ve been doing some research on this subject after I read in Joshua Block’s book, Effective Java, Item 1, about the use of static factory methods rather than building builders. There in the text he defends the use, whenever possible and cites, among other justifications, the possibility of implementing the standards Singleton or Flyweight. Also cite the case of the Class Boolean, who wisely uses the Flyweight through the method valueOf(boolean):

public static Boolean valueOf(boolean b) {
return b ? Boolean.TRUE : Boolean.FALSE;
}

My question is: I understand the advantages of using these Patterns, but would it not be possible to implement them in the constructor itself? Their use alone does not justify the creation of a static factory method.

1 answer

5


The constructor problem is that it allocates memory to the object you want or not, with the factory method you decide what to do.

In the case of Boolean it has 2 objects allocated and if you need to use thousands of times only these two will be allocated. With the constructor will create thousands of objects even if you can use the 2 existing objects these objects will be created (if nothing has changed as far as I have seen, they are 20 bytes each, apart from the pointer to reference it which nowadays is always 8 bytes).

A builder in the background does two things: memory allocation and initialization, if it only did the second then it would give to do it without the fascia.

In Java it is like this, other languages can allow.

It has disadvantage also to do so, after all it hides a possible allocation of memory. "Programmer Nterprise" in general does not care much for this and for this reason that they make application that consume many resources and then blame the poor Java (it is not the fault of language is the fault of the culture of the programmers who use it). Other programmers often worry about this and let explicit help think about whether or not to do it.

Some people argue that there should not even be pure builders and only Fabric Methods. It makes some sense, but I wanted a way to show whether or not to allocate.

  • And how do you deal with the issue of addiction injection when you become the private builder? It is possible to use DI when using this instance building strategy?

  • It’s something else, but it bears some resemblance.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.