Back couple of months ago I attended a presentation hosted by two representative of an independent software development company. It was mainly about good software design and practices.
The two guys were talking mainly about Java and I remember them saying, that in some circumstances it is very good practice to use getInstanceOf() instead of the constructor. It had something to do with making always calling getInstanceOf() from different classes rather than constructor and how it was it is much better approach on larger scale projects.
As you can see I cannot remember much from it now :/ but I remember that the arguments that they used were really convincing. I wonder if any of you ever came across such a design and when, would you say, is it useful? Or do you think it isn't at all?
Consider static factory methods instead of constructors—Joshua Bloch
They were probably talking about the static factory method pattern (and not the reflection API method for dynamically creating objects).
There at several advantages of a method such as getInstanceOf() over a constructor and using new. The static factory method can...
Choose to create a different sub-class of the main class if that is desirable in certain cases (based on environmental conditions, such as properties and other objects/singletons, or method parameters).
Choose to return an existing object instead of creating one. For an example of this, see Boolean.valueOf(boolean) in the Java API.
Do the same thing as the constructor - just return a new instance of the class itself.
Provide many different kinds of ways to construct a new object and name those methods so they are less confusing (e.g. try this with constructors and you soon have many different overloads). Sometimes this is not even possible with constructors if you need to be able to create an instance two different ways but only need the same type of parameters. Example:
// This class will not compile!
public class MyClass {
public MyClass(String name, int max) {
//init here
}
public MyClass(String name, int age) {
// init here
}
}
// This class will compile.
public class MyClass2 {
private MyClass2() {
}
public static MyClass2 getInstanceOfMax(String name, int max) {
MyClass2 m2 = new MyClass2();
// init here
return m2;
}
public static MyClass2 getInstanceOfAge(String name, int age) {
MyClass2 m2 = new MyClass2();
// init here
return m2;
}
}
Do any combination of the above.
And, on top of all that it hides the detail of instantiating an instance from other classes and so can be varied in the future (construction encapsulation).
A constructor can only ever create a new instance of an object of the exact type requested. It cannot be varied later.
Some disadvantages of this pattern are:
The factory methods are static so cannot be inherited in sub-classes; a parent constructor is easily accessible to sub-classes.
The factory method names can vary widely and this could be confusing for some (new) developers.
You also asked for personal experience. Yes, I frequently use both patterns. For most classes constructor but when there are much more advanced needs then I use the static factory. I also work on projects in other languages (proprietary, but similar to Java) where this form of construction is mandated.
I suspect you mean the newInstance method on the Class class. You would invoke it like this: MyClass foo = MyClass.newInstance();
This form of object instantiation is popular in creational patterns; it's useful when you want to specify the concrete, runtime type of an object externally, such as in a properties or XML file.
If Drew is right, newInstance() is part of the Java Reflection API. So it is not as natural as using a constructor.
Why it would be recommended to use it on a large project may come with the fact that it leads to Java Bean programming style and clearly makes the creation of the object something particular. On large project, creating object shouldn't be a cross-cutting concern but rather a clearly identified responsibility, often from one source / factory. But IMHO, you get all of those advantages and many more with IoC pattern.
Related
private static <T> String mapQueryResults(T objNew) {
T obj = new T();
...
}
It gives me error "Cannot instantiate the type T". How can I create an instance? Thanks
You cannot do this. Type T could be any type, including interfaces and abstract classes, which cannot be instantiated themselves. Even if a non-abstract class is passed, the empty constructor might not exist. If you wish to pass something to be able to create new instances of some class, then you could pass some factory class that creates these new instances for you through some method.
When topics like these come up, my approach is "forget programming and think logically."
The OP asked
create an instance by only using the passed parameter generic type
Basically, you want a constructor to build a concrete thing based on something generic. Is this possible in real life? Say that you need "something" built and you go to a builder and you tell the builder "I want you to build something for me" and provide no context, no additional information. Is it realistic to expect that the builder will be able to build what you need? Of course the answer is no. Unless you specify in sufficient detail a description of what you want, the builder is not going to know what to build.
T or "type", as others already mentioned, could be anything. If this was allowed by the language, you will most likely end up with nothing usable. It would be like having T be dough. Unless you specifically tell someone you want pizza, or bread, or flour tortillas, there is no way you can expect someone to make what you want if the only thing that is known is "dough."
Different "types" have different requirements for construction. In fact, some "types" cannot be built at all (they might have a private constructor). Others the constructor is hidden behind static factory methods. In short, there are too many reasons why this is simply not possible.
All that said, you are not really wrong thinking that there should be a way where you can pass a set of different "types" of parameters to some function and end up with different kinds of concrete objects built. If that is what you are thinking, then what you need is a Design Pattern (or patterns) that will support this notion.
In the original Gang of Four book, you will find 5 CREATIONAL Design Patterns:
Abstract Factory - factory that builds family of things (i.e. a factory of factories)
Builder - Builds the object in stages (typically when objects are too complex)
Factory Method - factory that build single type of object (or different things based on a common abstraction)
Prototype - Creates a new object based on another object
Singleton - Ensures a single instance is created
Based on the little information in the original post, I believe the OP needs to implement either a Factory Method or possibly a Prototype pattern.
You could change the method argument to accept a Supplier<T> constructor function, and pass in something like MyClass::new:
public class MyClass {
public MyClass() {}
public MyClass(String s) { ... }
}
public static void main(String[] args) {
mapQueryResults(MyClass::new);
mapQueryResults(() -> new MyClass("test"));
}
private static <T> String mapQueryResults(Supplier<T> objNew) {
T obj = objNew.get();
...
}
When the Gang of four introduced the singleton pattern, they also had to explain, why not to use static class fields and method instead. The reason was: the possibility to inherit. For Java it had sense - we cannot normally inherit the class fields and methods.
Later the "Effective Java" book appeared. And we know now that the existence of reflection destroys the singularity of the singleton class with private constructor. And the only way to make a real SINGLEton is to make it as a single item of an enumeration. Nice. I had done some myself this way.
But a question remains: While we cannot inherit from enumeration, what is the use of this singleton? Why we don't use these old good static/class fields and methods?
Edit. Thanks to the #bayou.io I see that in https://softwareengineering.stackexchange.com/a/204181/44104 there is a code that can trick the enum, too, and create again two exemplars of the enum singleton. The other problems are mentioned there, too. So, there is no need to use enum instead of the usual singleton class pattern, too? BTW, all enum pluses that are mentioned here till now, work for singleton classes, too.
what is the use of this singleton? Why we don't use these old good static/class fields and methods?
Because enum is an object so it can not only be passed around but also implement interfaces.
Also since we are making a class, we can use the different public/private options available to all kinds of classes.
So in practice, we can make a singleton that implements an interface and then pass it around in our code and the calling code is non the wiser. We can also make the enum class package private but still pass it around to other classes in other packages that expect the interface.
If we used the static methods version, then the calling class would have to know that this object is a singleton, and our singleton class would have to be public so the other classes can see it and use it's methods.
There's nothing particularly wrong with the "good old fashioned singleton", enum "singletons" are just convenient - it saves you the need to muck around with boiler-plated code that looks the same in every singelton.
To me, a singleton makes sense wherever you want to represent something which is unique in its kind.
As an example, if we wanted to model the Sun, it could not be a normal class, because there is only one Sun. However it makes sense to make it inherit from a Star class. In this case I would opt for a static instance, with a static getter.
To clarify, here is what I'm talking about :
public class Star {
private final String name;
private final double density, massInKg;
public Star(String name, double density, double massInKg) {
// ...
}
public void explode() {
// ...
}
}
public final class Sun extends Star {
public static final Sun INSTANCE = new Sun();
private Sun() { super("The shiniest of all", /**...**/, /**...**/); }
}
Sun can use all the methods of Star and define new ones. This would not be possible with an enum (extending a class, I mean).
If there is no need to model this kind of inheritance relationships, as you said, the enum becomes better suited, or at least easier and clearer. For example, if an application has a single ApplicationContext per JVM, it makes sense to have it as a singleton and it usually doesn't require to inherit from anything or to be extendable. I would then use an enum.
Note that in some languages such as Scala, there is a special keyword for singletons (object) which not only enables to easily define singletons but also completely replaces the notion of static method or field.
ENUM singletons are easy to write. It will occupy very less code, which is clean & elegant if you compare with implementation of lazy singleton with double synchronized blocks
public enum EasySingleton{
INSTANCE;
}
Creation of ENUM instance is thread safe.
ENUM singletons handled serialization by themselves.
conventional Singletons implementing Serializable interface are no longer remain Singleton because readObject() method always return a new instance just like constructor in Java. you can avoid that by using readResolve() method and discarding newly created instance by replacing with Singeton
private Object readResolve(){
return INSTANCE;
}
Have a look at this article on singleton
I am currently enrolled in a CS2 course (data structures) where Java is the language used and I am interested in comparing and contrasting object instantiation using the traditional constructor method v.s. a factory method. Does one represent a greater degree of computing elegance than the other? Would a factory method handle parameters in a manner similar to a parameterized constructor? E.g:
public class Tester
{
private String name;
private int age;
// Parameterized constructor
public Tester(String myName, int myAge)
{
this.name = myName;
this.age = myAge;
}
}
Essentially, I'm very curious on how one would write an equivalent factory method and what the potential benefits would be of doing so.
Thanks,
~Caitlin
Factory methods are nice as they can return a reference to an object that isn't necessarily an instance of that class. It can return that class, a subtype, or even null, and generally carry themselves on any way they want that a method can. You can thus move logic of selecting types into your own code. You can return an existing instance where appropriate, saving heap space and such.
Another basic pseudoexample is Integer.forValue() that can intern an integer, so identical immutable objects don't get recreated for no reason. Also see Executors.newXxxThreadPool().
A basic example:
public class Tester
{
private String name;
private int age;
// Parameterized constructor
private Tester(String myName, int myAge)
{
this.name = myName;
this.age = myAge;
}
public static Tester getTester(String mn, int ag){
if(age>0){return new Tester(mn, ag);}
else if(age>80){return new OldPersonThatExtendsTester(mn, ag);}
//we'd need a public or otherwise accessible constructor above. It's a subtype!
else {return null;} //yes, this is possible
}
}
According to the well-reasoned observations in Effective Java, the main advantages to static factory methods are as follows:
You can name them, unlike constructors which must always be named after the class. This makes code more readable and can avoid ugly situations where overloaded constructors might be impossible due to the types of arguments being the same, etc. In such a case, you could easily supply two factory methods with different names that indicate the difference.
A static factory method is not required to actually instaniate anything unlike a constructor which must create a new instance. Static factory methods are therefore essential for classes that are instance-controlled (eg. singleton classes).
Unlike constructors, a static factory method can return any object at all as long as the returned object matches or is a subclass of the return type. This enables interface-based type systems. The Enum framework of Java 1.5 makes use of this: the EnumSet class has no public constructors, only static factories. The actual object that is returned by the static factories varies depending on the size of the enum.
The main disadvantage of static factories is that they cannot be the basis of a class designed for inheritance. A class that provides only private constructors cannot be subclassed. A minor disadvantage of static factory methods is that they cannot be distinguished from other static methods, and so in order for them to be recognizable to the reader they usually follow naming patterns (they can be annotated if such a one is designed as a marker annotation for static factory methods).
A factory is useful in specific situations:
Where one of several different subclasses of the object might be returned, based on parameters.
Where there is some need to "guard" the creation of objects, perhaps for security, perhaps for some sort of synchronization.
Where created objects need to be "enrolled" somehow after creation, and doing so in the constructor is not feasible.
Where one does not even want to load the (actual) class (and it's tree of referenced classes) unless an instance must be created.
Where some reason such as the above is not present, there is no benefit to factory methods, and they simply obscure the logic.
There is no real restriction on what a factory can do, given that it can (if things are set up properly) access package level constructors and interfaces that are not accessible to the hoi polloi.
Added: To address the "inheritance" issue --
Let's say we have the classical Vehicle example, with Car and Truck subclasses. If you simply have CarFactory and TruckFactory then that increases the complexity of the code for no good reason (unless there are other compelling reasons for using factories).
But you can have a VehicleFactory and have it "decide", based on input or external factors, to create a Car or a Truck. This is a fairly common pattern.
However, if you were to (for some reason) have a VehicleFactory that only created Vehicle objects (not Cars or Trucks), and if use of the factory were mandatory (you couldn't access Vehicle's constructors), that would make it essentially impossible to subclass Vehicle. When you use a factory you make it very difficult (at the least) for someone else to add new subclasses.
This question already has answers here:
Constructors vs Factory Methods [closed]
(10 answers)
When to use a Constructor and when to use getInstance() method (static factory methods)?
(6 answers)
Closed 9 years ago.
Well, i have a very conceptual question. A lot of things look like fabrics, where i'm not sure where the great benefit is.
As example
public class MyObject {
public MyObject() {
}
public static MyObject create() {
return new MyObject();
}
public void doSomething(){
// some code...
};
}
The only benefits from my point of view is a bid less to code. In my opinion, no impact on performance happens. Are there other benefits?
MyObject myobject = new MyObject();
or
MyObjecct myobject = MyObject.create();
Thanks
You are correct in that there is no significant performance difference; and the reasons for using this form are primarily about readability of the code.
In general if you use the static create function you would declare the constructor private thus ensuring your users can ONLY create objects with the static function
In general I don't think the static create adds much to code, ad for ordinary everyday objects a new is probably clearer and more direct.
However there are some cases that I think the static constructor is useful:
For construction of large complicated objects, especially objects involving a lot of complexity in initialisation - often a simple constructor misleads library users into assuming the construction task is fast and easy.
If you have multiple constructors with ambiguous parameters you can use the static function name to make it more readable, for example you might have createFromFile(String FileName) and createFromJSONEncoding(String Data)
You want to control if a new object is ACTUALLY created - for example if this is a read-only resource you might be keeping a buffer of the resources already open and if the library user requests the same resource twice you can simply give them an already cached copy (as opposed to making a new duplicate copy)
Joshua Bloch addresses this concern in Effective Java, Chapter 2, Item 1: Consider static factory methods instead of constructors; here are a few highlights:
"One advantage of static factory methods is that, unlike constructors, they
have names." -- you can't have two different constructors that take an int argument, but you can have two static factory methods called createWithAge(int age) and createWithHeight(int height)
"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."
As you see, the concern is hardly related to performance (except for reusing cached instances), but mainly to object oriented design.
DISCLAIMER: Oops, I just saw the same answer (far better explained) already being posted for a different question: https://stackoverflow.com/a/3169644/262683. My bad...
There is no answer to this question.
The fact is that both patterns are legitimate ways to construct objects that are applicable to particular situations.
Static factory methods are important in situations where instance control is very important, such as in systems that maintain object caches or pools.
The new operator is apt for its simplicity and is rather important for classes that are designed for inheritance.
You are asking what is the best practice. The answer is that the best practice depends on your goals and, as always for questions of this sort, the best practice is that which makes smart use of available tools to reach a scalable and maintainable solution.
I suggest that this question be closed.
The case I see where you might need to use create:
You have to control creation of every instance of your class. For example, you count number of objects created or link them somehow and if number of instances reached your desired maximum throw exception.
Also factory pattern might be interesting to read about.
If you're not sure, just create via new
And if you choose to go with create you'd probably want to make your constructor private
It is a (simplistic) Factory Pattern. Please check the applicability section of the Wikipedia entry to see where it is used.
Now when you don't wan't any other class to create your class' object then you make you class constructor private:
private MyObject()
now any class wanting to create your class object will have to do this :
MyObjecct myobject = MyObject.create();
Because now doing this inside some other class MyObject myobject = new MyObject(); will cause compiler error.
There are a few topics similar to this, but I couldn't find one with a sufficient answer.
I would like to know what is the best practice for constructor overloading in Java. I already have my own thoughts on the subject, but I'd like to hear more advice.
I'm referring to both constructor overloading in a simple class and constructor overloading while inheriting an already overloaded class (meaning the base class has overloaded constructors).
Thanks :)
While there are no "official guidelines" I follow the principle of KISS and DRY. Make the overloaded constructors as simple as possible, and the simplest way is that they only call this(...). That way you only need to check and handle the parameters once and only once.
public class Simple {
public Simple() {
this(null);
}
public Simple(Resource r) {
this(r, null);
}
public Simple(Resource r1, Resource r2) {
// Guard statements, initialize resources or throw exceptions if
// the resources are wrong
if (r1 == null) {
r1 = new Resource();
}
if (r2 == null) {
r2 = new Resource();
}
// do whatever with resources
}
}
From a unit testing standpoint, it'll become easy to test the class since you can put in the resources into it. If the class has many resources (or collaborators as some OO-geeks call it), consider one of these two things:
Make a parameter class
public class SimpleParams {
Resource r1;
Resource r2;
// Imagine there are setters and getters here but I'm too lazy
// to write it out. you can make it the parameter class
// "immutable" if you don't have setters and only set the
// resources through the SimpleParams constructor
}
The constructor in Simple only either needs to split the SimpleParams parameter:
public Simple(SimpleParams params) {
this(params.getR1(), params.getR2());
}
…or make SimpleParams an attribute:
public Simple(Resource r1, Resource r2) {
this(new SimpleParams(r1, r2));
}
public Simple(SimpleParams params) {
this.params = params;
}
Make a factory class
Make a factory class that initializes the resources for you, which is favorable if initializing the resources is a bit difficult:
public interface ResourceFactory {
public Resource createR1();
public Resource createR2();
}
The constructor is then done in the same manner as with the parameter class:
public Simple(ResourceFactory factory) {
this(factory.createR1(), factory.createR2());
}
Make a combination of both
Yeah... you can mix and match both ways depending on what is easier for you at the time. Parameter classes and simple factory classes are pretty much the same thing considering the Simple class that they're used the same way.
I think the best practice is to have single primary constructor to which the overloaded constructors refer to by calling this() with the relevant parameter defaults. The reason for this is that it makes it much clearer what is the constructed state of the object is - really you can think of the primary constructor as the only real constructor, the others just delegate to it
One example of this might be JTable - the primary constructor takes a TableModel (plus column and selection models) and the other constructors call this primary constructor.
For subclasses where the superclass already has overloaded constructors, I would tend to assume that it is reasonable to treat any of the parent class's constructors as primary and think it is perfectly legitimate not to have a single primary constructor. For example,when extending Exception, I often provide 3 constructors, one taking just a String message, one taking a Throwable cause and the other taking both. Each of these constructors calls super directly.
If you have a very complex class with a lot of options of which only some combinations are valid, consider using a Builder. Works very well both codewise but also logically.
The Builder is a nested class with methods only designed to set fields, and then the ComplexClass constructor only takes such a Builder as an argument.
Edit: The ComplexClass constructor can ensure that the state in the Builder is valid. This is very hard to do if you just use setters on ComplexClass.
It really depends on the kind of classes as not all classes are created equal.
As general guideline I would suggest 2 options:
For value & immutable classes (Exception, Integer, DTOs and such) use single primary constructor as suggested in above answer
For everything else (session beans, services, mutable objects, JPA & JAXB entities and so on) use default constructor only with sensible defaults on all the properties so it can be used without additional configuration
Constructor overloading is like method overloading. Constructors can be overloaded to create objects in different ways.
The compiler differentiates constructors based on how many arguments are present in the constructor and other parameters like the order in which the arguments are passed.
For further details about java constructor, please visit https://tecloger.com/constructor-in-java/