Service provider framework in java - java

As per the book "Effecive java" what does the statement "The class of the object returned by a static factory method need not even exist
at the time the class containing the method is written." means in following paragraph:
The class of the object returned by a static factory method need not even exist
at the time the class containing the method is written. Such flexible static factory
methods form the basis of service provider frameworks, such as the Java Database
Connectivity API (JDBC). A service provider framework is a system in which
multiple service providers implement a service, and the system makes the implementations
available to its clients, decoupling them from the implementations

As per the book "Effecive java" what does the statement "The class of
the object returned by a static factory method need not even exist at
the time the class containing the method is written." means in
following paragraph:
A good way to explain what is meant by this sentence is to consider the EnumSet type, which is a class in the java.util package.
EnumSet is an abstract class without any accessible constructors. In order to get an EnumSet instance, the programmer uses one of its static factory methods, eg. EnumSet.of( ... ). For example:
Set<MyEnum> s = EnumSet.of(MyEnum.FIRST_CONSTANT);
The object returned by the of() method does not have an implementation type of EnumSet. Rather, the implementation type depends on the MyEnum class. If MyEnum has 64 or fewer constants, then the type of the object returned by of() is RegularEnumSet. If MyClass has more than 64 constants, the type of the object returned is JumboEnumSet. The actual type of the object returned, however, is of no interest to the programmer. All he or she cares about is getting some type of object that adheres to the EnumSet contract.
Now, let's say that, oh, five years later the Java language architects decide that it would be important to have another EnumSet implementation type, say, just for example, a cached enum implementation for classes with very large numbers of constants (more than 1024). They write this class to follow the EnumSet contract and call it:
final CachedEnumSet extends EnumSet {
:
:
}
Even though CachedEnumSet didn't exist when EnumSet was written, the fact that the use of static factories enabled a contract-based implementation system enabled the Java architects to add this new implementation years later.
Now, when a client invokes EnumSet.of(), he or she could get a RegularEnumSet object, a JumboEnumSet object, or the new CachedEnumSet object, but they wouldn't care because the object they get is still a subtype of EnumSet and is governed by its contract.

A factory method is generally going to be returning a class that implements an interface (or extends a class, same result either way). But the actual class to be returned may be defined dynamically. In that case, the class to be returned doesn't need to exist when the factory method is written.
May be easiest by example. The JDBC example is something like DriverManager - you provide a database connection URL. From that URL, the DriverManager needs to figure out which class to return. If you're using an Oracle database, it creates an Oracle driver class (which implements the JDBC APIs), even though DriverManager doesn't know anything about Oracle specifically.
As a general case, let's say our factory method returns interface AA. The implementation of the factory method might read a configuration file that defines the class to create, then use reflection to create that class at runtime. The defined class just needs to exist in the CLASSPATH. The factory method knows how to create it, but the implementation hadn't existed at the time the factory method was written.
There are lots of everyday examples where this sort of thing occurs: JDBC providers, custom logging appenders, XML providers.

Related

Why are there no subclasses of java.lang.Class?

java.lang.Class defines multiple methods which only apply to a certain type of class, e.g.:
getComponentType: Only relevant for arrays
getEnumConstants: Only relevant for enums
So why is there, for example, no ArrayClass which defines the getComponentType method instead?
This appears to be more or less a design choice. Since i did not design this language, i cannot answer it with certainty, but i'll try to explain potential reasons for this.
So why is there for example no ArrayClass which defines the getComponentType method instead?
The trick to understanding this is, that the java.lang.Class class is not a direct equivalent to the class you are coding. This specific class is only used to represent the created class at runtime (for example: for the use of reflections).
As from the Java-Doc of the Class (here from Java 7):
Instances of the class Class represent classes and interfaces in a running Java application. An enum is a kind of class and an annotation is a kind of interface. Every array also belongs to a class that is reflected as a Class object that is shared by all arrays with the same element type and number of dimensions. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.
You are writing custom classes, if you write your code, which means that your created code is the class. If you create a class called the ArrayClass, this is your class. The java.lang.Class class is then only usable at runtime to analyze the class of this specific Object.
For the design in Java, two more layers of complication are added.
First: You can analyze every object, which is a subtype of java.lang.Object. The method getClass is defined here. This means that you are able to introspect any object for any specific detail. If the specific type of the Object is not an enum for example, the class returns null upon calling getEnumConstants. If you had specific sub-types of the java.lang.Class, you would have to cast the instance before introspecting it, which would make it more annoying to work with.
Second: The java.lang.Class object, representing your type is created lazy, within the ClassLoader. Upon referenzing a specific type, the ClassLoader checks whether or not the Class is already loaded and if not, loads it. It then creates the java.lang.Class-Objects, which represents this specific Type. This class-object can then be used, to create instances of your type.
If the java language had different subtypes for the java.lang.Class, the ClassLoader would have to instantiate the correct subtype of the Class, corresponding to what would be needed. If you where able to create custom subtypes of the java.lang.Class, this would get out of hand quickly. How is the ClassLoader supposed to know which Class-instance is connected to your Type? Would you have to write specific Class-instances and somehow mark your created type to use that Class-instance? You could imagine something like this:
public class MyType extends ... implements ... type MyClassInstance
But then, how do you fill up custom fields within your custom java.lang.Class instance? Those complications may be the reason, that the java.lang.Class has a generic type, representing the connected Type. Event though there are a million possible solutions to those complications, there still might be an argument to be made for usability and robustness.
As Oracle point out in there Design Goals of the Java Programming Language:
The system that emerged to meet these needs is simple, so it can be easily programmed by most developers; familiar, so that current developers can easily learn the Java programming language; ...
As much as one would love to see something like this within the language, this feature would make it way more complicated, since it would allow developers to change the behavior of the newInstance method for example. You could introduce an Exception within this Method and one might think, the constructor threw an Exception, even though it did not. This goes into the same (or a similar) direction as Why doesn't Java offer operator overloading?, with that, you are essentially overriding the new keyword.
The Class currently is final (likely because it is a core language construct). This prohibits subtypes of java.lang.Class. If the class should receive subtypes, it has to loose final which means anyone could override any specific detail for a class. Calling getClass could result in any unknown type, that could do anything.
With that, we now only have specific subtypes of classes, we still cannot access them. To do this, we have to do one of the following:
Either add a generic type to the Object like this (i don't want to start a debate about super or extends, this is just an example):
public class Object<T extends Class> {
public final native T getClass();
}
This is required because we want to have certain classes connected to certain objects. With this however, we are not specifying how to instantiate the class. Normally a class is instantiated through the ClassLoader. Again from the JavaDoc:
Class has no public constructor. Instead Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader.
This would no longer be viable, except we require certain aspects like a private constructor. Also, we had to provide every custom Class as native C++ code.
The other possibility would be, to define the getClass method in implementations something like this (this code has different generic based issues, but again, just an example):
public class Object {
public <T extends Class<?>> T getClass() {...}
}
public class MyType {
public MyClass getClass() { return new MyClass(); }
}
Which would open the door to more complicated issues introduced earlier. You could now do work in here, that you are not supposed to do. Imagine a InvocationHandler for example. The other issue with this is that now the developer has the freedom to decide whether or not a Class is instantiated only once or multiple times, which would break for example the Class-Based-Programming and of course some aspects of the Java-Language.
Even though i cannot answer with certainty, i hope this helped a bit.

What does "Static factories returned object need not exist" mean?

While reading "Effective Java" J.Bloch came across this statement
A fifth advantage of static factories is that the class of the returned object need not exist when the class containing the method is written.
What does it mean? Can someone explain it with some examples ?
It means that the API of your static factory method can return an interface type, of which the implementation won't be written or generated until later.
As an example:
public static MyInterface getMyInterfaceInstance() {
//load instance dynamically and return it.
}
In this case, the factory method only needs the MyInterface interface to exist when it's being compiled. The actual implementation can be loaded dynamically at runtime in many ways, including:
Creating a proxy object
Reflection (configurable implementation class name loaded at runtime)
Looking up a service loader
In particular, the last two options simply mean that the implementation class can be written in a different module (and many modules can provide an implementation of the interface), and these implementation classes will be discovered at runtime - which makes it possible for the static factory method to be written before the actual implementation class.

State of Object, which don't has any attribute

We all know state of an Object is value of it's attributes (instance variables), but if class doesn't has any attribute (no inherited attributes), what would be the state of an Object of such class.
There is a word for such objects - stateless.
There is no such thing as a Java class without a parent class. The default parent would be used, e.g. java.lang.Object.
At a minimum every instance of a class has two attributes: a reference address and a Class type. Note, not every class can be instantiated. There is also some space used in the ClassLoader and any String(s) may (or may not) be interned. This actual implementation might vary slightly on the specific version of the JDK and run-time platform, and additional optimizations can be added by the JIT. However, as a Java developer you are not responsible for this memory management and I would be wary of premature optimization.
first thing
any class we write in java will extend Object class by default if there is no extends written by the developer.
so each and every class will definitely have a parent with no doubt atleast Object class.
second
if you dont put any attributes in your class , obviously it will get all the instance variables except private gets inherited to your class.
so it will have atleast object state but it will not serve any purpose
An object with no data members and links to other objects is a stateless object and in this form can hardly be of any use.
This kind of classes can nevertheless be usefull, because of its methods. It can be...
a base for a further inheritance. It declares/defines some methods, that could be inherited by derived classes. This class will probably be an abstract class, having no objects at all (although not a condition)
a service class. It can define some methods, which in nature do not belong to concrete objects but are used by other objects. Like some all-purpose mathematical operations, a service that returns a current time or similar. These methods can be static, so again no instances are needed.
We call those object stateless. As the name suggests, they have no state.
Referring to other answers/comments, even though every Java object implicitly extends Object, mind that Object has no fields. So even though every object has a runtime address and class attributes, for all practical purposes you can still consider some objects stateless.
Next, it is definitely not true that stateless objects serve no purpose! You can use stateless object for:
1) Grouping functions with similar functionality, similar to java.lang.Math, which groups mathematical functions.
2) Passing functionality as a parameter, e.g. Comparator<T> can be used to sort objects that do not implement Comparable<T>, and it definitely needs no state.
Stateless objects are somehow similar to immutable objects: their state can never be changed and therefore they are always thread-safe.
You may also want to see JEE Stateless Session Beans which differentiate between a converstional state and an instance state.

AbstractClass.getInstance() method is this an anti-pattern

In some places where a class hierarchy is present and the top most base class is an abstract class there is a static getInstance() method in the abstract class. This will be responsible for creating the correct sub-class and returning it to the caller. For example consider the below code.
public class abstract Product {
public static Product getInstance(String aCode) {
if ("a".equals(aCode) {
return new ProductA();
}
return ProductDefault();
}
// product behaviour methods
}
public class ProductA extends Product {}
public class ProductDefault extends Product {}
In Java, java.util.Calendar.getInstance() is one place this pattern has been followed. However this means each time a new subclass is introduced one has to modify the base class. i.e: Product class has to be modified in the above example. This seems to violate the ocp principle. Also the base class is aware about the sub class details which is again questionable.
My question is...
is the above pattern an anti-pattern ?
what are the draw-backs of using the above pattern ?
what alternatives can be followed instead ?
The interface is not an anti-pattern. But the way you've implemented it is rather poor ... for the reason you identified. A better idea would be to have some mechanism for registering factory objects for each code:
The Java class libraries do this kind of thing using SPIs and code that looks reflectively for "provider" classes to be dynamically loaded.
A simpler approach is to have a "registry" object, and populate it using dependency injection, or static initializers in the factory object classes, or a startup method that reads class names from a properties file, etcetera.
No it's not. It's more like factory method pattern http://en.wikipedia.org/wiki/Factory_method_pattern. E.g. Calendar.getInstance();. JDK is full of such examples. Also reminds of Effective Java Item 1: Consider static factory methods instead of constructors
There are a number of separate issues here.
getInstance is probably going to be a bad name. You explicitly want a new object you can play around with. "Create", "make", "new" or just leave that word out. "Instance" is also a pretty vacuous word in this context. If there is sufficient context from the class name leave it out, otherwise say what it is even if that is just a type name. If the method returns an immutable object, of is the convention (valueOf in olden times).
Putting it in an abstract base class (or in an interface if that were possible) is, as identified, not the best idea. In some cases an enumeration of all possible subtypes is appropriate - an enum obviously and really not that bad if you are going to use visitors anyway. Better to put it in a new file.
Anything to do with mutable statics is wrong. Whether it is reusing the same mutable instance, registration or doing something disgusting with the current thread. Don't do it or depend (direct or indirectly) on anything that does.
Based on the feedback i introduced a new ProductFactory class that took care of creating the correct Product. In my case the creation of the correct product instance depends on an external context (i've put the product code for the purpose of simplicity.. in the actual case it might be based on several parameters.. these could change over time). So having a Product.getInstance() method is not that suited because of the reasons outlined in the question. Also having a different ProductFactory means in the future.. Product class can become an interface if required. It just gives more extensibility.
I think when the creation of the object doesn't depend on an external context.. like in the case of Calendar.getInstance() it's perfectly ok to have such a method. In these situations the logic of finding the correct instance is internal to that particular module/class and doesn't depend on any externally provided information..

Google Guava Supplier Example

Please explain the use of the interface Supplier(in Guava) with a suitable example .
The Supplier interface is simply an abstraction of a no-arg function that returns a value... it is a means of getting some instance or instances of an object. Since it is so general, it can be used as many things. Jared explained how the Multimaps factories utilize it as a factory for creating a new instance of a Collection of some type for values.
Given the simplicity of the interface, it also allows for some very powerful decoration of a Supplier's behavior by wrapping it in another Supplier that alters its behavior somehow. Memoization is one example of that. I've used the Suppliers.memoizeWithExpiration method myself as an easy way to make it so some data will only be read from a server at most once in a given period of time.
I'd also recommend taking a look at Guice and how the Provider interface is used in it. Provider is exactly equivalent to Supplier and is central to how Guice works.
Provider allows users to define a custom way of creating new objects of a given class. Users can write a get() method which can execute whatever code is needed to create a new object, so they aren't limited to having Guice use constructors alone to create objects. Here, they are using it to define a custom factory for new instance of an object.
Guice allows injection of a Provider of any dependency. This may return a new instance every time get() is called or it may always return a single instance or anything in between, depending on how the binding the Provider represents is scoped. This also allows for "lazy instantiation" of dependencies... the Provider gives a class a means of creating an object without needing to actually create the object ahead of time. An instance of the object does not need to be created until when, and if, get() is called.
As indicated above, Providers form the basis of scoping in Guice. If you take a look at the Scope interface, you'll notice its single method Provider<T> scope(Key<T> key, Provider<T> unscoped) is defined in terms of Providers. This method takes something that creates a new instance of an object (the Provider<T> unscoped) and returns a Provider<T> based on that which applies whatever policy the scope defines, potentially returning some cached instance of the object rather than creating a new one. The default NO_SCOPE scope simply passes along the unscoped provider, meaning a new instance will be created each time. The SINGLETON scope caches the result of the first call to unscoped.get() and thereafter returns that single instance, ensuring that everything that depends on the singleton-scoped object gets a reference to that single object. Note that the Provider returned by the SINGLETON scope's scope method does essentially the same thing as the Supplier returned by Suppliers.memoize (though it's a bit more complicated).
The main reason we included Supplier in Guava was to support the Multimaps methods that generate arbitrary Multimaps, such as
public static <K,V> Multimap<K,V> newMultimap(Map<K,Collection<V>> map,
Supplier<? extends Collection<V>> factory)
The Supplier creates a Collection that holds all of the values for a given key. The Multimap uses the Supplier whenever you store a key-value pair with a key that's not already in the Multimap.
It's a way to provide an indirect object. You may want to provide another object each time Supplier.get() is called.
For example, i have a singleton class called SmtpMailSender, which takes a hostname for the smtp server. However, the hostname can change at runtime, so instead of taking a String hostname, it takes a Supplier<String> hostname.
Another example use of Supplier:
http://javawayoflife.blogspot.com/2010/06/unit-test-and-new-date.html
Another great use of the class is decoupling - if a component only uses another to obtain a value, do not depend on the concrete implementation, but on this interface.
Anyway, there is some example code here: http://www.slideshare.net/tfnico/google-guava
See the Suppliers class and I guess the methods there will somehow answer your question.

Categories

Resources