Creation of Objects: Constructors or Static Factory Methods - java

I am going through Effective Java and some of my things which I consider as standard are not suggested by the book, for instance creation of object, I was under the impression that constructors are the best way of doing it and books says we should make use of static factory methods, I am not able to few some advantages and so disadvantages and so am asking this question, here are the benefits of using it.
Advantages:
One advantage of static factory methods is that, unlike constructors, they
have names.
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.
A fourth advantage of static factory methods is that they reduce the verbosity
of creating parameterized type instances.
Disadvantages:
The main disadvantage of providing only static factory methods is that
classes without public or protected constructors cannot be subclassed.
A second disadvantage of static factory methods is that they are not
readily distinguishable from other static methods.
Reference: Effective Java, Joshua Bloch, Edition 2, pg: 5-10
I am not able to understand the fourth advantage and the second disadvantage and would appreciate if someone can explain those points. I would also like to understand how to decide to use whether to go for Constructor or Static Factory Method for Object Creation.

Advantage 4: When using a constructor, you have
Foo<Map<Key, Value>> foo = new Foo<Map<Key, Value>>();
vs
Foo<Map<Key, Value>> foo = Foo.createFoo(); // no need to repeat
this advantage will be gone in Java 7, when the diamond syntax will be introduced
Disadvantage 2. You can't easily tell whether a given static method is used for constructor, or for something else.
As for how to choose - there is no single recipe for that. You can weigh all of the above advantages and disadvantages given a use-case, but most often it will just be a decision driven by experience.

If you know the concrete type of the class you are trying to create, then calling the Constructor is fine.
Static Factory Methods are nice when you're not entirely sure how to construct the object you need.
The Factory Method still calls the Constructor on the concrete type, but the method handles the decision on what kind of concrete class to instantiate. The Factory Method then returns an Interface type (rather than a concrete type) so that the concrete type is hidden from the caller.

Disadvantage 2.
A static method that is used for object creation has the same functional layout and appearance as any other static function.
Just by looking at a static method that creates objects you wouldn't know it does this, and the opposite is the relevant part. When you're writing code that you're unfamiliar with, it can be difficult to identify the correct static method that is used to create objects.
The use of the Static Factory Pattern is well documented and can be very useful, especially in Singleton and Multiton situations. Also useful in the initialisation of complex objects.

Related

"Factory Method Design Pattern" in context of Java interfaces?

I am a beginner in Java and the book that I use to learn it seems to have cryptic examples and sentences that completely confuse me.
I understand what interfaces are and how/where to apply the concept in real world. But what are Factory Methods? The term "factory method" is ambiguous (JavaScript has a different meaning for that) so I am providing the snippet that the book has, in order to make my question clear. Here is the code:
interface Service {
void method1();
void method2();
}
interface ServiceFactory {
Service getService();
}
The Service interface is just a normal interface. ServiceFactory interface looks like a normal interface but it is a "Factory Method". What's that? What does it solve and why I should use them?
A factory method is simply a method that encaspulate the creation of an object. Instead of using the new operator as you normally would for creating an instead of a Service, in your example, you're using the factory method on some object.
ServiceFactory sf = new ServiceFactoryImpl();
// factory method
Service s = sf.getService();
To better illustrate the role of the method, it could be called createService instead. Now the method encapsulates the details of the creation of a Service, you can provide many flavors of the methods (by overloading), you can have it return different subclasses depending on the context, or parameters passed to the factory method.
A "factory method" is a method that constructs an object.
More specifically, the term usually refers to a static method that returns an instance of its declaring class (either a direct instance, or an instance of a subclass). In my experience, there are a few cases where that's particularly commonly done:
If you need to have multiple different constructors, using factory methods lets you give them appropriate names (whereas calls to different constructors can only be distinguished by the argument-types, which aren't always obvious at a glance).
If you need to have a few different implementations of a single abstract class that serves as the entry-point, the factory method can instantiate the appropriate subtype.
If you need any sort of caching logic or shared instances, the factory method can handle that, returning an already-existing instance if appropriate.
If you need to do some work with side effects, a factory method can be named in such a way that it's more clear what those side effects are.
So, your example doesn't really involve a "factory method" IMHO, but you can cheat a bit and describe getService() as one. (Rather, I would just describe ServiceFactory as a "factory" at leave it at that.) The benefits of ServiceFactory.getService() are the same as those of a factory method, plus the usual benefits of having an instance instead of a static method.

Why use a factory instead of 'new'?

I am reading the book EMF: Eclipse Modeling Framework where its stated:
The EMF programming model strongly encourages, but doesn’t require,
the use of factories for creating objects. Instead of simply using the
new operator to create [an object]...
Why is the use of factories encouraged over new?
Your answer does not have to be EMF specific, as long as it has to do with Java.
You can read Effective Java Item 1: Consider static factory methods instead of constructors. It describes advantages of using factory methods in detail:
One advantage of static factory methods is that, unlike constructors, they
have names
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.
A fourth advantage of static factory methods is that they reduce the verbosity of creating parameterized type instances (seems to be outdated since Java 7)
I agree with mostly every answers given here, but those arguments apply generally to every situation in Java, however in this particular case of EMF there is another additional reason: EMF has its own introspection mechanisms, which are used, for instance, for the serialization and deserialization, which doesn't rely in the Java reflection.
For the deserialization, for instance, it reads the XML file, and instantiate the Java objects using the Ecore model information and the respective Factories. Otherwise it would need to use Java reflection.
The answere here is not specific to Java too.
Factory methods have names, it's easier to remember, and less error-prone.
They do not require a new instance to be created each time they are called, you can use preconstructed classes and cache here.
They can return an object of any subtype not only the one called in new
You can parameterize calling "new" object.
The answer to this question is explained in Elegant Objects by Yegor Bugayenko, Chapter 1, Under "1.1 Never use -er names" section.
What the author says is:
A class is a factory of objects.
A class makes objects, though we usually phrase that by saying a class instantiates them:
class Cash {
public Cash(int dollars) {
//...
}
}
Cash five = new Cash(5);
This is different from what we call a Factory Pattern, but only because this "new" operator in Java is not as powerful as it could be. The only thing you can use it for is to make an instance—an object. If we ask class Cash to make a new object, we get a new object. There is no check for whether similar Objects already exist and can be reused, there are no parameters that would modify the behavior of new. etc.
"new" operator is a primitive control for a factory of objects.
Factory Pattern is a more powerful alternative to operator new, but conceptually they are the same. A class is a factory of objects. A class makes objects, keeps track of them, destroys them when necessary, etc.
A Factory Pattern, in Java, works like an extension to the new operator. It makes it more flexible and powerful, by adding an extra logic in front of it.
For example:
class Shapes {
public Shape make(String name) {
if (name.equals("circle")) {
return new Circle();
}
if (name.equals("rectangle")) {
return new Rectangle() ;
}
throw new IllegalArgumentException("not found");
}
}
This is a typical factory in Java that helps us instantiate objects, using textual names of their types. In the end, we still use the new operator. My point is that conceptually, there is not much difference between Factory Pattern and new operator. In a perfect OOP language this functionality would be available in the new operator.
Mainly it is simplicity of creating objects. It's a lot easier to call method from factory than to remember what each parameter in constructor means + it makes changes in code easier

Realistic use case for static factory method?

I'm familiar with the idea and benefits of a static factory method, as described in Joshua Bloch's Effective Java:
Factory methods have names, so you can have more than one factory method with the same signature, unlike constructors.
Factory methods don't have to create a new object; they can return a previously-created object. This is good for immutable objects or value objects.
Factory methods can return an object of any subtype of their return type, unlike constructors.
Now I'm trying to explain static factory methods for someone who is learning Java and OO principles. She learns best from concrete scenarios instead of abstractions. If she can see the pattern at work, solving some problem, she'll get it. But she finds it harder to read an abstract list of characteristics like the above to understand how to apply the pattern.
Can you help me come up with a realistic example of using a static factory method, that makes its benefits clear, but which is still simple enough to show someone in an introductory Java class?
This person does have programming experience in PL/SQL but never got around to learning OOP patterns.
Use javax.swing.BorderFactory as an example of all three points.
This class is used to make borders for swing objects. These border objects can be easily re-used, and this factory method allows for this. Here is the javadoc. This factory is a great example of all three points:
There are multiple static methods with different names like createEmptyBorder() and createEtchedBorder().
These methods will return previously created objects when possible. It's quite frequent that the same border would be used throughout an application.
Border itself is actually an interface, so all objects created through this factory are actually classes which implement this interface.
The textbook example of your second point is Integer.valueOf(int) (similar for Boolean, Short, Long, Byte). For parameter values -128 to 127, this method returns a cached instance instead of creating a new Integer. This makes (auto)boxing/unboxing much more performant for typical values.
You can't do that with new Integer() since the JLS requires that new create a new instance every time it is called.
My current favorite example of this pattern is Guava's ImmutableList. Instances of it can only be created by static factories or a builder. Here are some ways that this is advantageous:
Since ImmutableList doesn't expose any public or protected constructors, it can be subclassed within the package while not allowing users to subclass it (and potentially break its immutability guarantee).
Given that, its factory methods are all able to return specialized subclasses of it without exposing their types.
Its ImmutableList.of() factory method returns a singleton instance of EmptyImmutableList. This demonstrates how a static factory method doesn't need to create a new instance if it doesn't have to.
Its ImmutableList.of(E) method returns an instance of SingletonImmutableList which is optimized because it will only ever hold exactly 1 element.
Most of its other factory methods return a RegularImmutableList.
Its copyOf(Collection) static factory method also does not always need to create a new instance... if the Collection it is given is itself an ImmutableList, it can just return that!
Wouldn't Calendar.getInstance() be a good exmaple?
It creates depending on the locale a BuddhistCalendar, JapaneseImperialCalendar or by default a GregorianCalendar.
Here is one I had to do a while back. At a job interview, I was asked to program a deck of cards where they can be shuffled. Really simple problem. I created:
Card:
suit
rank
Deck:
card[]
I think what was the distinguishing factor is that there can only 52 cards at all times. So I made the constructor for Card() private and instead create static factory valueOf(suit, rank) This allowed me to cache the 52 cards and make the immutable. It taught many important basic lessons in that books.
immutable
control creation of object
static methods
possibly subclassing and return a card from another source. ( I didn't do this)
This is similar to Boolean and Byte, except I used a common homework example to show why its important to control the instances. I also created a helper function for deck called newDeck() because I wanted to show an instance where the constructor might not need to be private but it would still be nice to have a helper static factory.
I hope this helps!
The simple case. Suppose you have a class which operates some sort of printer, but it doesn't care if it is epson, canon or something else. So, you just create an Interface Printer, create some implementations of it and create a class which has only one method: createPrinter.
So, the code will be simple:
public interface Printer {
print();
}
class CanonPrinter implements Printer {
print() {
// ...
}
}
public PrinterFactory {
Printer createPrinter() {
if (... ) {
return new CanonPrinter();
} else {
return new EpsonPrinter();
}
}
}
client code:
Printer printer = PrinterFactory.createPrinter();
printer.print();
Here you abstract you clinet code from any details of what printers you can operate with or how they manage printing. It's PrinterFactory who cares what printer to choose if one for example malfunctions.

Single instance with methods in java

I am wondering about programming decision - which I think is matter of style.
I need to have single instance of class which has only methods and no attributes.
To obtain that in java I have two options:
create an abstract class with static methods within, thus it will not be possible to create any instance of the class and that is fine,
use a singleton pattern with public methods.
I tend to go for second approach although met with 1. Which and why is better of those, or there is third option.
Would it make sense for that singleton to implement an interface, allowing you to mock out those methods for test purposes?
I know it goes against testing dogma these days, but in certain situations I think a static method is fine. If it's the kind of behaviour which you're never going to want to fake for test purposes, and which is never going to be polymorphic with other implementations, I don't see much point in making a singleton. (Singletons are also generally the enemy of testability, although if you only directly refer to them in the injection part of your code, they can implement appropriate interfaces so their singletoneity never becomes a problem.)
It's worth mentioning that C# has "static classes" for this kind of situation - not only do they prohibit other code from deriving from or instantiating the class, but you can't even use it as a parameter. Basically it signals the intent very clearly.
I would definitely suggest at least having a private constructor to prevent instantiation by the outside world.
My personal view is that the class should contain a private constructor and NOT be abstract. Abstract suggest to a reader that there is a concrete version of the class somewhere, and they may waste time searching for it. I would also make sure you comment your code effectively.
public class myClass {
/** This class should never be instantiated. */
private myClass() {
}
public static void myMethod() {
}
...
//etc
...
}
For option #1, it may not even be that important to restrict instantiation of your static utility class. Since all it has is static methods and no state, there is no point - but neither harm - instantiating it. Similarly, static methods can't be overridden so it does not make sense - nor difference - if it is subclassed.
If it had any state, though - or if there is a chance that it will get stateful one day - it may be better to implement it as a normal class. Still I would prefer not to use it as a Singleton, rather to pass its sole instance around via dependency injection. This makes unit testing so much easier in the long run.
If it holds a state I would use the singleton pattern with private constructors so you can only instantiate from within the class. If it does not hold a state, like the apache commons utility classes, I would use the static methods.
I've never seen the problem with static methods. You can think of static methods as somehow breaking OO, but they make perfect sense if you think of static as a marker that something is stateless. You find this in the java apis in places like java.Math. If you're worried about subclassing you can always make it final.
There is a danger in that a class like that can end up as a "utility method garbage can", but as long as the functionality doesn't diverge too much then there's nothing wrong with it.
It's also clearer, as there's no need to manage an object lifecycle like you would with a singleton (and since there's no state, what's the point of that anyway?).
For a single instance, I suggest you have an enum, with one instance.
However, for a class with no attributes, you don't have to have an instance. You can use a utility class. You can use an enum, with no instances and only static methods. Note: this cannot be easily mocked out.
You can still implement an interface if you ever need to mock out the implementation in testing.

Is there a rule of thumb for when to code a static method vs an instance method?

I'm learning Java (and OOP) and although it might irrelevant for where I'm at right now, I was wondering if SO could share some common pitfalls or good design practices.
One important thing to remember is that static methods cannot be overridden by a subclass. References to a static method in your code essentially tie it to that implementation. When using instance methods, behavior can be varied based on the type of the instance. You can take advantage of polymorphism. Static methods are more suited to utilitarian types of operations where the behavior is set in stone. Things like base 64 encoding or calculating a checksum for instance.
I don't think any of the answers get to the heart of the OO reason of when to choose one or the other. Sure, use an instance method when you need to deal with instance members, but you could make all of your members public and then code a static method that takes in an instance of the class as an argument. Hello C.
You need to think about the messages the object you are designing responds to. Those will always be your instance methods. If you think about your objects this way, you'll almost never have static methods. Static members are ok in certain circumstances.
Notable exceptions that come to mind are the Factory Method and Singleton (use sparingly) patterns. Exercise caution when you are tempted to write a "helper" class, for from there, it is a slippery slope into procedural programming.
If the implementation of a method can be expressed completely in terms of the public interface (without downcasting) of your class, then it may be a good candidate for a static "utility" method. This allows you to maintain a minimal interface while still providing the convenience methods that clients of the code may use a lot. As Scott Meyers explains, this approach encourages encapsulation by minimizing the amount of code impacted by a change to the internal implementation of a class. Here's another interesting article by Herb Sutter picking apart std::basic_string deciding what methods should be members and what shouldn't.
In a language like Java or C++, I'll admit that the static methods make the code less elegant so there's still a tradeoff. In C#, extension methods can give you the best of both worlds.
If the operation will need to be overridden by a sub-class for some reason, then of course it must be an instance method in which case you'll need to think about all the factors that go into designing a class for inheritance.
My rule of thumb is: if the method performs anything related to a specific instance of a class, regardless of whether it needs to use class instance variables. If you can consider a situation where you might need to use a certain method without necessarily referring to an instance of the class, then the method should definitely be static (class). If this method also happens to need to make use of instance variables in certain cases, then it is probably best to create a separate instance method that calls the static method and passes the instance variables. Performance-wise I believe there is negligible difference (at least in .NET, though I would imagine it would be very similar for Java).
If you keep state ( a value ) of an object and the method is used to access, or modify the state then you should use an instance method.
Even if the method does not alter the state ( an utility function ) I would recommend you to use an instance method. Mostly because this way you can have a subclass that perform a different action.
For the rest you could use an static method.
:)
This thread looks relevant: Method can be made static, but should it? The difference's between C# and Java won't impact its relevance (I think).
Your default choice should be an instance method.
If it uses an instance variable it must be an instance method.
If not, it's up to you, but if you find yourself with a lot of static methods and/or static non-final variables, you probably want to extract all the static stuff into a new class instance. (A bunch of static methods and members is a singleton, but a really annoying one, having a real singleton object would be better--a regular object that there happens to be one of, the best!).
Basically, the rule of thumb is if it uses any data specific to the object, instance. So Math.max is static but BigInteger.bitCount() is instance. It obviously gets more complicated as your domain model does, and there are border-line cases, but the general idea is simple.
I would use an instance method by default. The advantage is that behavior can be overridden in a subclass or if you are coding against interfaces, an alternative implementation of the collaborator can be used. This is really useful for flexibility in testing code.
Static references are baked into your implementation and can't change. I find static useful for short utility methods. If the contents of your static method are very large, you may want to think about breaking responsibility into one or more separate objects and letting those collaborate with the client code as object instances.
IMHO, if you can make it a static method (without having to change it structure) then make it a static method. It is faster, and simpler.
If you know you will want to override the method, I suggest you write a unit test where you actually do this and so it is no longer appropriate to make it static. If that sounds like too much hard work, then don't make it an instance method.
Generally, You shouldn't add functionality as soon as you imagine a use one day (that way madness lies), you should only add functionality you know you actually need.
For a longer explanation...
http://en.wikipedia.org/wiki/You_Ain%27t_Gonna_Need_It
http://c2.com/xp/YouArentGonnaNeedIt.html
the issue with static methods is that you are breaking one of the core Object Oriented principles as you are coupled to an implementation. You want to support the open close principle and have your class implement an interface that describes the dependency (in a behavioral abstract sense) and then have your classes depend on that innterface. Much easier to extend after that point going forward . ..
My static methods are always one of the following:
Private "helper" methods that evaluate a formula useful only to that class.
Factory methods (Foo.getInstance() etc.)
In a "utility" class that is final, has a private constructor and contains nothing other than public static methods (e.g. com.google.common.collect.Maps)
I will not make a method static just because it does not refer to any instance variables.

Categories

Resources