static factory method question! - java

in this site it says that a new object isnt being created each time , which leads to efficiency, but by what i can see an object is being created each time in the static method..
do not need to create a new object
upon each invocation - objects can be
cached and reused, if necessary.
http://www.javapractices.com/topic/TopicAction.do?Id=21
so why are the static factory methods are so efficient?
isnt writing something like this : Object obj=new Object is same as if i did Object obj=Someclass.GetObj();
class Someclass
{
public static Object GetObj()
{
return new Object
}
}
There is caching, but a new object is created either way...

Objects can be cached and reused. They aren't always. There are a number of other advantages, like:
better naming of the method
returning subclasses
There is an item in Effective Java for that, so go ahead and read it. The book is a must-read anyway.
Update: as I said, object can be cached. But it depends on the implementation. The one you show does not cache them. The one shown by Peter caches them. You have that option. With a constructor - you don't.

They are more flexible - for example if the input parameters for new object are not valid, you can return null or some null object implementation (=instance, which does nothing, but will not break your code by NullPointerException), or, as previously mentioned by others, you can cache created instances. There is another benefit from using factory methods over constructors - you can name them whatever you like, which can be more readable, if there are multiple constructors with lots of optional parameters.
EDIT: if you want to use only one instance, you can use this simple factory:
class Someclass{
private static Object o=new Object();
public static Object getObj(){
return o;
}
}

When you use new Object(), a new Object has to be created.
If you use a static factory, it can optionally create a new object, or it can reuse an existing one.
A simple example is using Integer.valueOf(int) instead of new Integer(int). The static factory has a cache of small integers and can save to the creation of a significant portion of integers. For some use cases this can be all the integers used. The later case will always create a new object which is relatively inefficient.

The link you presented provides very different explanation of a Factory Pattern. Generally factory pattern is used to obtain instances of classes whcih implement same interface but provide different behavior for the same contract. It allows us to choose different implementation at run time. Check out the example here:
http://www.allapplabs.com/java_design_patterns/factory_pattern.htm
Factory pattern is not generally used for caching objects. Singleton pattern is defined to ensure only one instance of the object is created.

The idea is that you use them as a strategy. If later you want to implement caching, you just change that method and add it in there. Compare this with having "new Bla()" scattered all over the code, and trying to implement caching for the Bla class.
Since the method is static, and usually just a few lines of code, it means it can be resolved at compile time, and even inlined.
Thus there is no advantage of using "new Bla()" instead of factory methods at all.

Using factory in some situations you could make your code more flexible, faster and also better readable.
For example, imagine, you have to write class which download some data from url
public class WavAudio {
private byte[] raw;
private static HashMap<String,WavAudio> cache;
private WavAudio(byte[] raw){
this.raw=raw;
}
public static loadFromUrl(String someUrl){
//If data has been loaded previously we don't have to do this more (faster..)
if (cache.containsKey(someUrl))
return cache.get(someUrl);
//Else we'll load data (that would take some time)
InputStream ires=(new URL(someUrl)).openStream();
ByteArrayOutputStream baos=new ByteArrayOutputStream();
byte[] raw = new byte[4096];
int nBytesRead;
while ((nBytesRead = ires.read(raw, 0, raw.length))>0)
baos.write(raw, 0, raw);
byte[] downloaded=baos.toByteArray();
WavAudio curr=new WavAudio(raw);
cache.put(someUrl,raw);
return raw;
}
public static void main(String[] args){
WavAudio wav=WavAudio.loadFromUrl("http://someUrl_1");
SomePlayer.play(wav); //the first melody is playing
WavAudio wav=WavAudio.loadFromUrl("http://someUrl_2");
SomePlayer.play(wav); //the second melody is playing
//won't be downloaded twice
WavAudio wav=WavAudio.loadFromUrl("http://someUrl_1");
SomePlayer.play(wav);
}
}

Related

Some classes need initialization and some don't

I already tried to search for an answer on the "using the new keyword" but didn't found an answer on my specific question.
Why do some classes have to be created with the keyword new and some don't
For example :
import java.io.BufferedReader
If you want to use this you have to create a new instance
BufferedReader read = new BufferedReader (..............)
But for example with system.console which also needs an import java.io.console. when you want to use this you can just type Console c = system.console()
i'm a beginner in Java and OO programming and found a couple of this examples troughout my book.
Thx for the help
In java, fields(aka Attributes) are always associated to either instance or to class.
There could be many instances of a class and to create instance you have to use new operator. To access instance related attributes, you will need to create one and this will be accessed as
ClassName instanceName = new ClassName();
instanceName.methorOrAttributeNameGoesHere
For class associated attribute aka Static attribute can be direcly accessed as ClassName.methorOrAttributeNameGoesHere
These are very basics of Java and probably you should first read some good book on Java and OOP like 'Head First Java'
The simple answer to this is that instantiation like new BufferedReader() always creates a different instance each time you call it; invoking a method like System.console() might or might not give you different instance.
Ultimately, all objects are instantiated via new; you just might not see it in your code.
Here are a couple of ways in which System.console() might be implemented (totally simplified, not actually like it is):
// (1) Returns new instance each time
class System {
static Console console() {
return new Console();
}
}
or
// (2) Returns same instance each time
class System {
private static final Console CONSOLE = new Console();
static Console console() {
return CONSOLE;
}
}
(There are infinitely more ways to implement it, these are just two examples. You can see the way it is implemented in OpenJDK by looking at the source code - it is similar to (2), in that the same instance is returned each time, just with a few more complications that I don't want to describe here)
In (1), if you invoke System.console() twice, you will get back two different instances of Console:
System.console() != System.console()
In (2), if you invoke System.console() twice, you will get back the same instance of Console:
System.console() == System.console()
The question I would ask here is do I need to care if I get back different instances or the same instance? The answer is probably not, if the API designer has done a reasonable job.
The decision as to whether expose the creation of a new Console was made by the person who wrote the classes. There are a number of reasons why he/she might not want you to create a different instance each time you invoke that method, e.g.:
The thing you are creating might be very expensive (slow, takes up lots of resources etc), so you don't want to create lots of them;
The thing you want has logically just one instance (it is a singleton).
There are a number of reasons why he/she might want you to create a separate instance each time you invoke that method, e.g.:
You don't want all of the places using that instance to share state. You have to worry about things like thread safety when instances of mutable classes are shared.
And there are a number of reasons why you might not want the user to invoke the constructor directly:
new Console() creates an instance of Console exactly; things like consoles are often platform-dependent, so you might actually want an instance of WindowsConsole, MacConsole etc to be returned when run on Windows, MacOS etc. If WindowsConsole and MacConsole extend Console, either of these can be returned from the System.console() method.
Prior to the introduction of the diamond operator <> in Java 7, it was necessary to include the full generic parameters in the new statement, e.g. ArrayList<HashMap<String, List<String>>> list = new ArrayList<HashMap<String, List<String>>>();; however, generic methods allowed this to be written as ArrayList<HashMap<String, List<String>>> list = newList():
<T> List<T> newList() { return new ArrayList<T>(); }
(Sometimes, you need a lot of parameters to pass to the constructor, and it is convenient to use the Builder Pattern. This isn't relevant to the cases in the question, but it is a reason for not invoking the constructor directly.)
The thing is that these are internal implementation details, and should be encapsulated: you, as a user of the Console class, shouldn't need to care about how expensive it is to create, or whether there is shared state: you just want a Console.
This encapsulation is effected by providing a method like System.console(): you don't need to know whether the method is implemented like (1) or (2) above (or any other method).
Additionally, if the class is originally written like (1), and that proves to be problematic, its implementation can be changed to (2) without you, as a user of the System class, needing to update your code.
This might be a bit too much detail for a beginner, and I can try to help you understand more; the long and short of it is that sometimes it is be better if you don't create instances directly.
System.console,console is static thats why we are calling it with class name directly,and to call the non static method we generally used the objectname.methodname .
The java.io.Console class is attached with system console internally.System class provides a static method console() that returns the unique instance of Console class.Thats why we used to do as Console c = system.console();
Please read about Static classes and non static classes method invocation/instance creation for more details.
Static methods don't require an instance, but non-static methods do. System.console() is static, butnew BufferedReader(...).read(...) is not
Static methods are typically used when the outcome of the method will never change based on the context. For instance:
Math.abs(-3); //will always be 3, no matter what
However consider this class:
public class Person {
private String name;
public Person(String name){
this.name = name;
}
public String getName() {
return name;
}
/*
* In this world, no special characters are allowed in a person's name
*/
public static boolean isValidName(String name) {
if (name.contains("!#$%&(=?") {
return false;
}
return true;
}
}
Person mySister = new Person("Mary");
Person myBrother = new Person("David");
Calling Person.getName() doesn't make any sense; this is like asking "What is a person's name?" without specifying who the person is. Now if you ask me "What is your sister's name?", then I can call mySister.getName() and give you a sensible answer.
Re: your comment "how do you know when to not use new"
If you are trying to create a new Person object (imagine you just had a baby), but you are wondering whether or not that amazing name you found on the internet will be accepted by the authorities:
boolean validName1 = Person.isValidName("LordVoldeMort!!!!!"); //returns false
boolean validName2 = Person.isValidName("HarryPotter2016"); //returns true
Person myLittleBabySon = new Person("HarryPotter2016"); //Accepted by authorities

what is the difference in java objects created with "new" and the ones that do not use "new"

What is the difference between creating an object with and without "new"?
example:
Thing someThing = new Thing();
vs.
Path filePath = Path.get("C:\\......)
In the first example I understand that when instantiating the object, that "new" is allocating memory for a the someThing object and that the memory location is referenced by someThing.
My text book says " You create a Path object" by using the second example. Is the difference just how the object is stored or memory is allocated? I am not sure why you would create an object this way.
In the second case you are using a static method which is internally creating the object or passing a reference to an existing object. This is a common pattern particularly when the APIs wish to hide an internal implementation (as is the case here).
There is no difference. The second example is a factory method.
You pass in a few parameters and that method will call new at some point on the actual instance class of the Path.
While it behaves like a constructor, there are also differences which should be pointed out: Static factory methods do not have to return the current type, but can also return a subtype, where in contrast a constructor creates an instance of the current class. (Hypothetical) Example:
public static Path create(String name) {
return new AbsolutePath(name); // subclass/implementation of Path
}
From an implementation point, this gives you a lot of flexibility for later extensions. You can for example implement some logic, which decides which concrete type to create within the method. You could cache instances and return them. You could return the same instance every time (Singleton). Etc.
Further aspect: You can actually give meaningful names to static factory methods, so code is easier to read:
public static Path createAbsolute(String name) { ... }
public static Path createRelative(String name) { ... }
With the first option you are sure you are creating a new object (more or less, java.lang.* classe are a bit special)
Let's take the second option:
Path filePath = Path.get("C:\\......)
Nothing assures you the instance you are storing in filePath is a Path one, it can be an instance of a subclass of Path. Something similar occurs with Calendar: Calendar is an abstract class, so
Calendar c=Calendar.getInstance();
The variable c is actually a GregorianCalendar.
Another difference:
class Singleton {
private Singleton s=null;
private Singleton(){};
public static Singleton getSingleton() {
if (s==null) {
s=new Singleton();
}
return s;
}
}
No matter how many times you call getSingleton, you will only create one object.
when you are using new keyword then an object of the particular class is created.
Here Thing someThing = new Thing();
something is an object of Thing class
Path filePath = Path.get("C:\......)
Path is a class having static method get() which accepts String arguments and it returns Path something like
public static Path get(String arg)
{
return path;
}
The memory is allocated by the method call to Path.get in the second instance. This allows the library to go through its own initialisation routines for a Path variable and which may perform additional checks. New just allocates memory. The memory may also be sorted and stored internally in some structure too, such that it doesn't constantly reload the same object via caching. I, personally, always call the factory methods rather than new up an object myself, however it could be considered to be a style thing, as pretty much everything that may be done with a factory method may also be achieved via a constructor.
In your examples, you are assuming that an object is created without a "new". That is an incorrect assumption. The object was created with "new" in the second example as well.
Just because you can't see the "new" doesn't mean it's not called in the function.

How much more expensive is the creation of an object without data in Java instead of the use of static methods?

Java lacks the ability to specify interfaces for static methods. A method in an interface must be non static. This makes it impossible to specify requirements for Classes. Instead one is limited to specify requirements for Objects. This makes it also impossible for example to specify the singleton functionality in an interface, because in Java the singleton pattern requires to be implemented as a static method. Here is a nice article, which explains it, but it is only in German.
When one is forced to implement something as a functionality of an object instead of the functionality of a class, an instance of this object has to be created, before the functionality can be used. But such object has some special characteristic: it has no state, because class functionality has no state either. Theoretically the instance creation of an object without data can be optimized to an NOP, because all methods can be linked to the class instead of any object. Java could implement some kind of implicit singleton functionality.
But how it this actually handled?
Think about some kind of functionality without any state.
interface Adder<T> { T add(T ... arguments); }
Basically it would be sufficient to implement this as a static method:
class IntegerAdder implements Adder<Integer> {
public static Integer add (Integer ... arguments) { }
}
But because Java does not allow static interface methods it has to be implemented in a non static way. The result is, that when ever an IntegerAdder is required one has to create an instance.
IntegerAdder integer_adder = new IntegerAdder();
Integer a = 1;
Integer b = 2;
Integer c = integer_adder.add (1, 2);
I fear this might be slower than the version without the instance creation:
Integer a = 1;
Integer b = 2;
Integer c = IntegerAdder.add (1, 2);
But how much slower is it in reality? Is it possible for the Java compiler to optimize the first version in that way that it performs as fast as the second one? And is this actually done?
You can create an instance of IntegerAdder once and reuse it, it is thread safe. Also pay attention that Integer ... arguments leads to 1) using objects instead of primitive ints 2) creating an array to pass parameters. Both things should be avoided if performance is concern

Java Constructor and static method

When should I use a constructor and when should I use static method?
Can you explain above with small snippet? I skimmed through a few threads but I'm still not clear with this.
Joshua Bloch advises to favor static factory methods instead of constructors (which I think is a good practice). Couple of advantages and disadvantages :
Advantages of static factory methods :
unlike constructors, they have names
unlike constructors, they are not required to create a new object each time they're invoked (you can cache instances : e.g. Boolean.valueOf(..)
unlike constructors, they can return an object of any subtype of their return type (great flexibility)
Disadvantages of static factory methods :
They are not really distiguishable from other static methods (it's hard to find out how to initialize an object if you are not familiar with the API)
The main disadvantage (if you use only static factory methods, and make constructors private) is that you cannot subclass that class.
Use a public constructor when you only ever want to return a new object that type and you want simplicity.
A good example is StringBuilder as it's mutable and you are likely to want a new object each time.
public String toString() {
StringBuilder sb = new StringBuilder();
// append fields to the sb
return sb.toString();
}
Use a static factor method when you might want to re-use objects (esp if immutable), you might want to return a sub-class or you want descriptice construction. A good example is EnumSet which has a number of static factories which do different things even though some have the same arguments.
EnumSet.noneOf(RetentionPolicy.class);
// has the same arguments, but is not the same as
EnumSet.allOf(RetentionPolicy.class);
In this case, using a static factory makes it clear what the difference between these two ways of construction the set.
Also EnumSet can return two different implementations, one optimised for enums with a small number of values (<= 64) RegularEnumSet and another for many values called JumboEnumSet
Always use a constructor if your class has a state (even for a single instance; singleton pattern ).
Only use static for utility methods like in java.lang.Math
Example:
public static int max(int a, int b) {
return (a >= b) ? a : b;
}
Doesn't change any state (instance variables) of an object, thus it can be declared static.
Use constructor when you need an object and other stuffs like functions and variables having one copy for every object.
when you want to do something without creating object then use static method.
Example:
public class Test {
public int value;
public static int staticValue;
public int getValue() {
return ++value;
}
public static int getStaticValue() {
return ++staticValue;
}
}
public class TestClass {
public static void main(String[] args) {
Test obj = new Test();
Test obj1 = new Test();
S.o.p(obj.getValue());
S.o.p(obj1.getValue));
S.o.p(Test.getStaticValue());
S.o.p(Test.getStaticValue());
}
}
Static factory methods have names, constructors don't. Thus factory methods can carry natural documentation about what they do that constructors can't. For example, see the factory methods in the Guava Libraries, like ImmutableMap.copyOf(otherMap). While this might have little effect on behaviour of construction, it has a huge effect on readability of the code. Definitely consider this if you're publishing an API.
Also you can use a factory when you need to do any more complicated configuration of the object you're creating, especially if you need to publish to other threads (registering in pools, exposing as an MBean, all manner of other things...) to avoid racy publication. (See e.g. Java Concurrency In Practice section 3.2)
Static methods that do something (e.g. Math.min) are not really the same thing as static factories, which can be considered direct replacements for constructors, with added flexibility, evolvability and (often) clarity.
Whenever you need to create an instance of an object you will have to use the constructor.
So, if you want to create a Car object, then you will need a constructor for that.
The keyword static means, that your method can be called without creating an instance.
class Car
{
private int num_of_seats;
public Car(int number_of_seats)
{
this.num_of_seats = number_of_seats;
}
// You want to get the name of the class that has to do with
// this class, but it's not bounded with any data of the class
// itself. So you don't need any instance of the class, and
// you can declare it as static.
static String getClassName()
{
return "[Car]";
}
}
In general you will use static class with data that are not correlated with the instance of the object.
Another example is:
class Ring
{
private List nodes;
public Ring(List nodes)
{
this.nodes = nodes;
}
// You want to calculate the distance of two ids on the ring, but
// you don't care about the ring. You care only about the ids.
// However, this functionality logical falls into the notion of
// the ring, that's why you put it here and you can declare it
// as static. That way you don't have to manage the instance of
// ring.
static double calculateDistance(int id_1, int id_2)
{
return (id_1 - id_2)/383; // The divisor is just random just like the calculation.
}
}
As the posts above say, it's just a matter of what you want to do and how you want to do it. Also, don't try to understand everything rightaway, write some code then try different approaches of that code and try to understand what your code does. Examples are good, but you need to write and then understand what you did. I think it's the only way you will figure out
why you do staff the way you have to do.
Static methods do not have to instantiate new objects everytime. Since object instantiation is expensive it allows instances to be cached within the object. So, it can improve performance.
This is the explanation from the Effective Java :
This allows immutable classes (Item 15) to use preconstructed
instances, or to cache instances as they’re constructed, and dispense
them repeatedly to avoid creating unnecessary duplicate objects. The
Boolean.valueOf(boolean) method illustrates this technique: it never
creates an object. This technique is similar to the Flyweight pattern
[Gamma95, p. 195]. It can greatly improve performance if equivalent
objects are requested often, especially if they are expensive to
create.
i.e. if you want to use a singleton, which means that you have only one instance of the object, which might be shared with others, then you need a static method, which will internally will call the constructor. So, every time someone wants an instance of that object you will return always the same, thus you will consume memory only for one. You always need a constructor in object oriented programming, in every OO language. In java an in many other languages the default constructor of an object is implied, and built automatically. But you need some custom functionality you have to make your own.
Above you see a few good examples of the usage. However, if you have something specific in your mind, please let us know. I mean if you have a specific case where you are not sure if you should use a static method or a constructor. Anyhow, you will definitely need a constructor, but I am not sure about the static method.

public static factory method

First of all please forgive me if its a really dumb question, I am just trying to learn this language to its core. I am reading Effective Java and the very first chapter talks about Static factory methods vs. Constructors. Their pros and cons. Few things that are confusing to me are:
class of an object returned by static factory method is nonpublic - what exactly does it mean?
unlike constructors static factory methods are not required to create a new object each time they are invoked - How does this happen? I am invoking factory method only to obtain a new object and do we put a check in factory method for checking if object already exists?
Thanks.
class of an object returned by static factory method is nonpublic -
what exactly does it mean?
It means that the actual class of the objects returned by a static factory method can be a subclass of the declared type, and this subclass does not have to be public. It's just another implementation detail that client code should not care about.
unlike constructors static factory methods are not required to create a new object each > time they are invoked - How does this happen? I am invoking factory method only to obtain a new object and do we put a check in factory method for checking if object already exists?
Yes, that's one way this could be done. But really, anything is possible.
First off, kudos to you for your choice in Java-lit: Bloch's book is an excellent primer.
To answer your 2nd question ('unlike constructors static factory methods are not required to create a new object each time they are invoked'), it's important to realize that what Bloch is saying here is that with a static factory you have the option of either: returning a new object or returning a pre-existing one. It all depends on what you want to do.
For example, let's suppose you have a really simple value class of type Money. Your static factory method probably should return a new instance -- that is, a new object with a specific value for Money. So, like this:
public class Money {
private Money(String amount) { ... } /* Note the 'private'-constructor */
public static Money newInstance(String amount) {
return new Money(amount);
}
}
But let's say you have some object that manages some resource and you want to synchronize access to that resource through some ResourceManager class. In that case you probably want your static factory method to return the same instance of itself to everyone -- forcing everyone to go through that same instance, so that that 1 instance can control the process. This follows the singleton-pattern. Something like this:
public ResourceManager {
private final static ResourceManager me = new ResourceManager();
private ResourceManager() { ... } /* Note the 'private'-constructor */
public static ResourceManager getSingleton() {
return ResourceManager.me;
}
}
The above method forces your user to only ever be able to use a single instance, allowing you to precisely control who(and when) has access to whatever it is you are managing.
To answer your first question, consider this (admittedly not the best example, it's pretty ad-hoc):
public class Money {
private Money(String amount) { ... }
public static Money getLocalizedMoney( MoneyType localizedMoneyType, String amount ) {
switch( localizedMoneyType ) {
case MoneyType.US:
return new Money_US( amount );
case MoneyType.BR:
return new Money_BR( amount );
default:
return new Money_US( amount );
}
}
}
public class Money_US extends Money { ... }
public class Money_BR extends Money { ... }
Note how I can now do this:
Money money = Money.getLocalizedMoney( user_selected_money_type );
saveLocalizedMoney( money );
Again, a really contrived-example but hopefully it helps you see more or less what Bloch was getting at with that point.
The other answers were good -- I just think that, as a beginner, sometimes it helps to see some actual code.
When you use the new keyword then you as the developer know that the JDK will create a new instace of that object. What the author is saying, when you use a static method, the developer no longer knows if the method is creating a new instance or possibly doing something else. Something else can be, reusing cached data, object pooling, creating a private implementation and returning a subclass of the class.
class of an object returned by static factory method is nonpublic
Frequently a static factory method will return either an an object typed as an interface (most common), or sometimes some base class (less common). In either case, you don't know the exact class of the returned object.
The advantage of this is getting an object whose behaviour you know without worrying about the messy details of what class it instantiates.
unlike constructors static factory methods are not required to create a new object each time they are invoked
To understand this, consider the case of working with a singleton. You may call .getInstance() on some factory classes to get the singleton instance of an certain object. Typically, what this does is create an instance of the object if it doesn't already exist, or give you the existing instance if it already does. In either case, you get back a copy of the object. But you don't (and won't) know if this singleton had to be created, or if one had already been constructed previously.
The advantage of this is that the lifecycle of the object and when it is created is managed for you.
Both of your questions can be answered by looking at some code that makes use of both of these properties of static factory methods. I suggest looking at Guava's ImmutableList.
Note how the no-arg factory method of() always returns the same instance (it doesn't create a new instance each time). If you look carefully, you'll also notice that its copyOf(Iterable) factory method actually returns the object that is passed to it if that object is itself an ImmutableList. Both of these are taking advantage of the fact that an ImmutableList is guaranteed to never change.
Notice also how various factory methods in it return different subclasses, such as EmptyImmutableList, SingletonImmutableList and RegularImmutableList, without exposing the types of those objects. The method signatures just show that they return ImmutableList, and all subclasses of ImmutableList have package-private (default) visibility, making them invisible to library users. This gives all the advantages of multiple implementation classes without adding any complexity from the user's perspective, since they are only allowed to view ImmutableList as a single type.
In addition to ImmutableList, most instantiable classes in Guava utilize static factory methods. Guava also exemplifies a lot of the principles set forth in Effective Java (not surprising, given that it was designed by those principles and with guidance from Josh Bloch himself), so you may find it useful to take a look at it more as you're working through the book.

Categories