Static Factory method Advantages - java

I was reading effective java and one advantage of static factory methods written is that they can return an object of any sub-type of return type.
I understood the way we can implement this as mentioned in following link with example.
https://www.slideshare.net/mysky14/java-static-factory-methods
But in the book an example of Collections API is given that has static factory methods in java.util.Collections utility class and it is written that "Collections API is much smaller than it would have been had it exported 32 separate public classes".
It is also mentioned that in this manner, API can return objects without their classes to be public and this results in very compact API.
I want to know how the API size is reduced by implementing this method and not having separate public classes.

I want to know how the API size is reduced by implementing this method and not having separate public classes.
Let's use the same concrete example used in the book: java.util.EnumSet has static factories that return one of two implementations: RegularEnumSet or JumboEnumSet. These implementations have their own complexities, but are effectively hidden to the clients of Collections. In theory, the factories could use other implementations in the future, and the clients of them would not be affected.
If you visualized this in a class diagram, the factory methods (e.g., of(), as opposed to a constructor) return an abstract type EnumSet, which hides the details of the implementations. Abstract (or Interface) types effectively abstract (simplify) the API.
What's more, the implementations are actually package private, meaning they're declared without a public keyword. This means that only classes in the same package can see them, so it prevents having Client depend on them. This is a great example of information hiding, which allows API developers to simplify their API and also to change the hidden parts later without breaking the code.
Another example that comes to mind where factory methods can simplify an API are the concrete iterators in Collections. In this case, it's a factory method that is not static, e.g., ArrayList.iterator(), that returns a concrete iterator for ArrayLists. The name of this class is even less "known" than the EnumSet implementations.

In general having static factory method would take out your object instantiation logic out of your class. Suppose based on certain logic, you need to return different subclass objects. This would result in if-else logic in your class method whichever is responsible for appropriate object instantiation. Moving this out to static factory method would result in cleaner class design which would be easier to test and closer to "Closed to modification" principle

Related

What is use of assaigning subclass object to superclass reference variable [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does it mean to “program to an interface”?
I keep coming across this term:
Program to an interface.
What exactly does it mean? A real life design scenario would be highly appreciated.
To put it simply, instead of writing your classes in a way that says
I depend on this specific class to do my work
you write it in a way that says
I depend on any class that does this stuff to do my work.
The first example represents a class that depends on a specific concrete implementation to do its work. Inherently, that's not very flexible.
The second example represents a class written to an interface. It doesn't care what concrete object you use, it just cares that it implements certain behavior. This makes the class much more flexible, as it can be provided with any number of concrete implementations to do its work.
As an example, a particular class may need to perform some logging. If you write the class to depend on a TextFileLogger, the class is forever forced to write out its log records to a text file. If you want to change the behavior of the logging, you must change the class itself. The class is tightly coupled with its logger.
If, however, you write the class to depend on an ILogger interface, and then provide the class with a TextFileLogger, you will have accomplished the same thing, but with the added benefit of being much more flexible. You are able to provide any other type of ILogger at will, without changing the class itself. The class and its logger are now loosely coupled, and your class is much more flexible.
An interface is a collection of related methods, that only contains the signatures of those methods - not the actual implementation.
If a class implements an interface (class Car implements IDrivable) it has to provide code for all signatures defined in the interface.
Basic example:
You have to classes Car and Bike. Both implement the interface IDrivable:
interface IDrivable
{
void accelerate();
void brake();
}
class Car implements IDrivable
{
void accelerate()
{ System.out.println("Vroom"); }
void brake()
{ System.out.println("Queeeeek");}
}
class Bike implements IDrivable
{
void accelerate()
{ System.out.println("Rattle, Rattle, ..."); }
void brake()
{ System.out.println("..."); }
}
Now let's assume you have a collection of objects, that are all "drivable" (their classes all implement IDrivable):
List<IDrivable> vehicleList = new ArrayList<IDrivable>();
list.add(new Car());
list.add(new Car());
list.add(new Bike());
list.add(new Car());
list.add(new Bike());
list.add(new Bike());
If you now want to loop over that collection, you can rely on the fact, that every object in that collection implements accelerate():
for(IDrivable vehicle: vehicleList)
{
vehicle.accelerate(); //this could be a bike or a car, or anything that implements IDrivable
}
By calling that interface method you are not programming to an implementation but to an interface - a contract that ensures that the call target implements a certain functionality.
The same behavior could be achieved using inheritance, but deriving from a common base class results in tight coupling which can be avoided using interfaces.
Polymorphism depends on programming to an interface, not an implementation.
There are two benefits to manipulating objects solely in terms of the interface defined by abstract classes:
Clients remain unaware of the specific types of objects they use, as long as the objects adhere to the interface that clients expect.
Clients remain unaware of the classes that implement these objects. Clients only know about the abstract class(es) defining the interface.
This so greatly reduces implementation dependencies between subsystems that it leads to this principle of programming to an interface.
See the Factory Method pattern for further reasoning of this design.
Source: "Design Patterns: Elements of Reusable Object-Oriented Software" by G.O.F.
Also See: Factory Pattern. When to use factory methods?
Real-world examples are applenty. One of them:
For JDBC, you are using the interface java.sql.Connection. However, each JDBC driver provides its own implementation of Connection. You don't have to know anything about the particular implementation, because it conforms to the Connection interface.
Another one is from the java collections framework. There is a java.util.Collection interface, which defines size, add and remove methods (among many others). So you can use all types of collections interchangeably. Let's say you have the following:
public float calculateCoefficient(Collection collection) {
return collection.size() * something / somethingElse;
}
And two other methods that invoke this one. One of the other methods uses a LinkedList because it's more efficient for it's purposes, and the other uses a TreeSet.
Because both LinkedList and TreeSet implement the Collection interface, you can use only one method to perform the coefficient calculation. No need to duplicate your code.
And here comes the "program to an interface" - you don't care how exactly is the size() method implemented, you know that it should return the size of the collection - i.e. you have programmed to the Collection interface, rather than to LinkedList and TreeSet in particular.
But my advice is to find a reading - perhaps a book ("Thinking in Java" for example) - where the concept is explained in details.
Every object has an exposed interface. A collection has Add, Remove, At, etc. A socket may have Send, Receive, Close and so on.
Every object you can actually get a reference to has a concrete implementation of these interfaces.
Both of these things are obvious, however what is somewhat less obvious...
Your code shouldn't rely on the implementation details of an object, just its published interface.
If you take it to an extreme, you'd only code against Collection<T> and so on (rather than ArrayList<T>). More practically, just make sure you could swap in something conceptually identical without breaking your code.
To hammer out the Collection<T> example: you have a collection of something, you're actually using ArrayList<T> because why not. You should make sure you're code isn't going to break if, say, you end up using LinkedList<T> in the future.
"Programming to an interface" happens when you use libraries, other code you depend upon in your own code. Then, the way that other code represents itself to you, the method names, its parameters, return values etc make up the interface you have to program to. So it's about how you use third-party code.
It also means, you don't have to care about the internals of the code you depend on, as long as the interface stays the same, your code is safe (well, more or less...)
Technically there are finer details, like language concepts called "interfaces" in Java for example.
If you want to find out more, you could ask what "Implementing an Interface" means...
I think this is one of Erich Gamma's mantras. I can't find the first time he described it (before the GOF book), but you can see it discussed in an interview at: http://www.artima.com/lejava/articles/designprinciples.html
It basically means that the only part of the library which you're going to use you should rely upon is it's API (Application programming interface) and that you shouldn't base your application on the concrete implementation of the library.
eg. Supposed you have a library that gives you a stack. The class gives you a couple of methods. Let's say push, pop, isempty and top. You should write your application relying only on these. One way to violate this would be to peek inside and find out that the stack is implemented using an array of some kind so that if you pop from an empty stack, you'd get some kind of Index exception and to then catch this rather than to rely on the isempty method which the class provides. The former approach would fail if the library provider switched from using an array to using some kind of list while the latter would still work assuming that the provider kept his API still working.

Why do we have separate Spliterators class in Java 8?

Why did new Spliterators class appear in Java 8? Since Java 8 we have possibility to add static methods to the interfaces.
Since Spliterators class has only static method wouldn't be simpler to declare all its methods in the Spliterator interface?
The same question about Collectors/Collector pair.
Thank you.
It’s perfectly possible that this decision was made without even thinking about this brand new possibility, but simply following the established-since-twenty-years pattern.
Besides that, it can be debated whether it is really useful to add 25 to 30 static methods to an interface. It makes sense to offer a few factories for canonical implementations, but you should draw a line somewhere. It’s not feasible to add factories to all implementations to an interface, just because they are offered by the same library. But this debate would be off-topic.
Further, Spliterators does not only offer static methods, but also nested classes. Unlike static methods, these classes would pollute the name space of every implementation class, when being defined in an interface.
Collectors and Spliterators may also contain implementation-specific non-public methods and even fields.
No, is not good idea, because interface declares a contract, but class represents logic. But after add default method to interface in Java 8 we can only declare public method, but in abstract class we can add public and private abstract method, so we still can hide some logic in abstract classes. Imagine, in actual level of language you can declare only public method, and everyone can change your idea for e.q. Collection
Because there is a difference between an interface and a class. These two have different intentions. Interface declares a contract. Default methods for the interface should be used carefully, for instance, where you can't break compatibility by adding a method declaration into an interface and can't declare xxxV2 interface.
A class is an entity, which represents a unit of the program logic.

Using an interface with only default methods as a utility class substitute

I have an interface whose implementors all require a common method internally - it is not required to be part of the public interface. Also, there are future interfaces in the pipeline that will need this functionality.
Is it good design to have this interface implement a different interface that just has this default method implemented? This way all implementors have access to the common method seamlessly. But, since there is no concept of 'private default' methods, the method is also exposed to clients, which I feel isn't right.
Is resorting to a separate concrete utils class a better means to this end? Or creating an abstract implementation of my interface with the required method and have clients extend that?
EDIT: My question is more inclined towards finding out whether an interface with only default methods is sound, design-wise? Having static methods in the interface does not seem to be in contention actually.
interface is used to segregate the users and the implementors. In your situation, i think an abstract class is more suitable.
default methods are overridable methods, but your scenario describes a utility method that is intended to be neither, part of the API nor overridable. Note that since default methods can work on the instance only in terms of the public methods defined in the interface, i.e. can not access any internals, there is no difference between:
interface MyInterface {
default ReturnType method(Parameter parameter) {
}
}
and
interface MyInterface {
static ReturnType method(MyInterface instance, Parameter parameter) {
}
}
regarding what the method can do. It’s only that within the default method, you may omit the qualifying this. when invoking other interface method, whereas in the static method, using instance. is mandatory. But in either case, you may invoke all public methods of the MyInterface instance but nothing else.
But the static method is not overridable and you may move it to any other class to avoid it becoming part of MyInterface’s API. But note that there is little reason to worry about the accessibility of the utility method. Since it can’t access any internals of the implementation classes, it can’t offer anything that the callers couldn’t do otherwise. It only makes it more comfortable than re‑implementing the functionality at the caller’s site. So moving the method into another class primarily documents the intention of not being part of the MyInterface’s API. It’s no harm, if the method is public there (to support implementations in arbitrary packages).
See for example the methods in the class StreamSupport. They are there to aid implementing Streams, needed by different packages, but not part of the Stream interface API itself. The fact that the methods there are public does not create any harm, they don’t offer anything you couldn’t do yourself using the other available public APIs. But it’s convenient for implementors not needing to do it themselves.

Calling the sub class method from super class isn't best practice?

I am working on a project where we have an abstract class(BaseConverter) with one abstract method(convert()) and few concrete methods. One important concrete method is invokeConverter() which will basically call the convert() method implemented in the subclass.
While our code is being reviewed by other guy, he told that, subclass methods shouldn't be called from superclass and he told it is not best practice. Below is our class structure. Can someone please tell whether this isn't a right way to do?
#Named
public abstract class BaseConverter{
#Inject
private ConversionDriver conversionDriver;//this class is responsible to return the correct subclass object based on the type
protected abstract String convert(Object toConvert);
public String invokeConverter(ConverterType type, Object toConvert){
conversionDriver.getConverter(type).convert(toConvert);//getConverter() return the subclass object based on the type
}
....
....
}
It is actually a design pattern called Template Method by GoF. However, you should not over apply it as it favors inheritance over composition.
Define the skeleton of an algorithm in an operation, deferring some
steps to subclasses. Template Method lets subclasses redefine certain
steps of an algorithm without changing the algorithm's structure.
You'll find this pattern implemented in many known frameworks and plugins. But, you should consider different patterns like the Strategy or the Decorator in some cases.
For instance, while Strategy pattern uses delegation to vary the whole algorithm, Template Method uses the defamed inheritance to vary a specific part of an algorithm. Strategy also modifies the logic of individual objects at run-time, while the Template Method modifies the logic of the entire class at compile-time by subclassing.
Regarding "best practice" - it is a controversial term. I believe that the Template Method should be replaced in favor of a better design pattern when the code base grows and refactoring for a better complexity is needed.
But sometimes it is the best solution for your needs. For example, you might have doExecute() method and would like other programmers to extend your class (whilst not modifying it), so you let them hook into the parts of your code providing a beforeExecute() method. Mature system would maybe include an event dispatcher capabilities if we talked about combination of various objects.

Regarding static in all the methods of the classes

I was going through java class in which I found all the methods were static , I want to know when there is the requirement or where the condition arises when we have to prefix static in front of all the methods. Is it any kind of design pattern..?
This is typically used in utilities classes. Think for example the Math class. You don't need an instance of an object to calculate the minimum of 2 numbers, so it makes sense that Math.min is a static method.
However, overuse of static methods / fields is not necessarily a good design practice.
Exactly: utility pattern
http://en.wikipedia.org/wiki/Utility_pattern
Helper classes usually provide static only methods. These are classes that provide some methods that are not specific just to one kind of object, but can be shared across the entire project. For instance, a MathHelper could define a method for calculating the average of an array of float values, another one for calculating the distance between 2 points and so on.
Classes which have all static methods are used for below purposes :
1) Copied from Joshua Bloch Effective Java
Interfaces can’t have static methods, so by convention, static factory methods for
an interface named Type are put in a noninstantiable class (Item 4) named Types.
For example, the Java Collections Framework has thirty-two convenience
implementations of its collection interfaces, providing unmodifiable collections,
synchronized collections, and the like. Nearly all of these implementations are
exported via static factory methods in one noninstantiable class (java.util.Collections).
The classes of the returned objects are all nonpublic.
2) Utility Pattern as suggested by #tgoossens

Categories