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/
Related
I want to write bean-friendly classes. I have observed a tendency (mostly with beans) to move required parameters to setters from the constructor (and use an init() method when done setting up the initial state).
This method concerns me because I want my classes to be usable without a bean infrastructure, just as Java objects. As I imagine I'd have to check for the proper state of the object in every method assert style.
Quick demo for the above:
class A {
public int x;
public int y;
private int sum;
private boolean initialized = false;
public void init() {
sum = x + y;
initialized = true;
}
private void initCheck() {
if (!initialized) {
throw new IllegalStateException("Uninitialized object.");
}
}
public int getXMulSum() {
initCheck();
return x * sum;
}
public int getYMulSum() {
initCheck();
return y * sum;
}
}
Is there a better practice?
Given that you don't want to use a framework...
If a class is not fit for use until it has been initialised, I would prefer using constructors. Don't be swayed by blogs and books. Constructors are there for this purpose. Using constructors also removes any requirement to synchronize your code.
One reason I can see for not using constructors, is if there is a lot of initialisation code and perhaps dependencies external to the class. If too much logic resides in a constructor, then it can make your application brittle and difficult to recover from Exceptions in the constructor. In this case you have the option of using a Factory class that will handle the instantiation and initialisation of the bean. This way, the calling code only ever receives a bean that is ready and fit for use.
A good pattern to use is the Builder pattern where you have a long list of constructor arguments.
"I have observed a tendency (mostly with beans) to move required parameters to setters from the constructor"
The main reason for this testability. If you can test a feature of the bean without having to initialise "expensive" dependencies, than not having them in the constructor is of benefit. Having said that, I would also argue that if this is an issue, you probably have too much functionality in your bean and you'd be better off breaking it up. As suggested by the Single responsibility principle.
The setters are more general than constructor arguments because they allow you to handle circular dependencies.
If you don't have circular dependencies, I'd recommend staying with constructor arguments, exacly for the purpose of enforsing the dependencies.
However, if at all possible, do not put any logic into constructor. As Brad said, it makes the application brittle. The entire Spring environment may not be available during constructor.
Try to design in a way that allows the constructor to simply remember the references for later use in the real methids. Avoid init() method if you can.
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.
I have been challenged by a design issue which I will try to describe below.
Suppose that a class, call it A, has a constructor with a bunch of parameters. Since it is tiring and dirty to write all those parameters in each instantiation, I have written another class, call it StyleSheetA, which encapsulates all those parameters and is the only parameter to the constructor of A. In this way, I can prepare some default StyleSheetA templates to be used later, and if it is needed, I can modify them.
And at this point, I need to extend A. Suppose B extends A. B will have its own stylesheet, namely StyleSheetB. I think it will be appropriate that StyleSheetB extends StyleSheetA, so with one stylesheet parameter, constructor of B can also construct its super class A. But I am afraid of the possibility that this design may have flaws. For example what if I decide to add a getter/setter for the stylesheet? Is there a novel way to handle all these situations? Am I in the wrong way? For those who are confused, I attach some code here:
class A
{
StyleSheetA ss;
A(StyleSheetA ss)
{
this.ss = ss;
// Do some stuff with ingredients of styleSheet
}
}
class StyleSheetA
{
int n1;
int n2;
// :
// :
int n100;
}
class B extends A
{
B(StyleSheetB ss)
{
super(ss);
// Do some stuff with ingredients of styleSheet
}
}
class StyleSheetB extends StyleSheetA
{
int n101;
int n102;
// :
// :
int n200;
}
Thank you for any help or suggestions, also any of your critics will be appreciated.
Edit: I am developing in java me so there is no generics support.
It seems to me that you are only moving the problem of having too many parameters from class A to class StyleSheetA.
To illustrate my point, think of this question: How would you instantiate StyleSheetA? Probably using a constructor that accepts all these parameters, anyway. The only benefit this design may give you is if you have a same set of parameter values encapsulated by an object of StyleSheetA which you will reuse among multiple instances of A. If so, bear in mind that although you'd have different instances of A they would share the same parameters, so it isn't a good choice.
What I could recommend you is to try to refactor your class A itself. Try to break it up into smaller classes. If nesseccary, try to create subclasses to avoid conditional branches, etc.
Now, I don't know how your class A looks like, but maybe if you do so you'll have several classes, each with its own set of parameters. And if any of the parameters is a discriminator (meaning that it determines the class "type") you will be able to get rid of it, just by using subclasses, and relying on built in type system to do it instead.
Have you considered using an IoC container, like StructureMap, to manage your constructor dependencies? That might make a lot of this stuff easier.
A thoughts on the getter and setter issue:
The constructor in 'B' implies that the additional parameters (n101+) are necessary for the operation of the class. If you were just extending the class with a full parameter list, you would have getters and setters for n101...n200 in B and n1...n100 in A. This suggests perhaps not having StylesheetB extend StylesheetA, but rather have the constructor to class B be B(StyleSheetA,StyleSheetB), this way you can have a setter in class A for it's parameters, have that inherited and also put one in B for StylesheetB.
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.
I was reading some Java recently and came across something (an idiom?) new to me: in the program, classes with multiple constructors would also always include a blank constructor. For example:
public class Genotype {
private boolean bits[];
private int rating;
private int length;
private Random random;
public Genotype() { // <= THIS is the bandit, this one right here
random = new Random();
}
/* creates a Random genetoype */
public Genotype(int length, Random r) {
random = r;
this.length = length;
bits = new boolean[length];
for(int i=0;i<length;i++) {
bits[i] =random.nextBoolean();
}
}
/* copy constructor */
public Genotype(Genotype g,Random r) {
random = r;
bits = new boolean[g.length];
rating = g.rating;
length = g.length;
for(int i=0;i<length;i++) {
bits[i] = g.bits[i];
}
}
}
The first constructor doesn't seem to be a "real" constructor, it seems as though in every case one of the other constructors will be used. So why is that constructor defined at all?
I am not sure that the code you were reading was high quality (I've reviewed some bioinformatics code in the past and it is unfortunately often not written by professional developers). For example, that third constructor is not a copy constructor and generally there are problems in this code, so I wouldn't "read too much into it".
The first constructor is a default constructor. It only initializes the bare minimum and lets users set the rest with getters and setters. Other constructors are often "convenience constructors" that help create objects with less calls. However, this can often lead to inconsistencies between constructors. In fact, there is recent research that shows that a default constructor with subsequent calls to setters is preferable.
There are also certain cases where a default constructor is critical. For example, certain frameworks like digester (used to create objects directly from XML) use default constructors. JavaBeans in general use default constructors, etc.
Also, some classes inherit from other classes. you may see a default constructor when the initialization of the parent object is "good enough".
In this specific case, if that constructor was not defined, one would have to know all the details in advance. That is not always preferable.
And finally, some IDEs automatically generate a default constructor, it is possible that whoever wrote the class was afraid to eliminate it.
Is the object Serializable?
To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable if this is not the case. The error will be detected at runtime.
During deserialization, the fields of non-serializable classes will be initialized using the public or protected no-arg constructor of the class. A no-arg constructor must be accessible to the subclass that is serializable. The fields of serializable subclasses will be restored from the stream
Yes, I agree the "blank" constructor should not always exist (in my experience beginners often make this mistake), although there are cases when blank constructor would suffice. However if the blank constructor violates the invariant that all the members are properly instantiated after construction, blank constructor should not be used. If the constructor is complicated, it is better to divide the construction into several protected/private methods. Then use a static method or another Factory class to call the protected methods for construction, as needed.
What I wrote above is the ideal scenario. However, frameworks like spring remove the constructor logic out of the code and into some xml configuration files. You may have getter and setter functions, but probably may be avoided from the interface, as described here.
Default constructor is NOT mandatory.
If no constructors defined in the class then default (empty) constructor will be created automatically. If you've provided any parametrized constructor(s) then default constructor will not be created automatically and it's better to create it by yourself. Frameworks that use dependency injection and dynamic proxy creation at runtime usually require default constructor. So, it depends on use cases of class that you write.
The default constructor is'nt a good pratice for the functional view.
The default constructor is used if the object have a global visibility into a method: for example, you want log the actual state of a object in a try/catch
you can code
MyObejct myObject=null
try{...
}catch(Exception e){
log.error(myObject);//maybe print null. information?
}
or do you prefer
MyObejct myObject=new Object();
try{...
}catch(Exception e){
log.error(myObject);//sure print myobject.toString, never null. More information
}
?
Anotherway the create a EMPTY object have'nt a lot of logic, but instatiate a NULL object is harmuful in my opinion.
You can read this post
That is NOT a copy constructor. Basically you want empty constructors when working with some framework. Shall there always be an empty constructor, of course, public or private, but at least it allows you to keep control of how the class is being (or not) instantiated.
I usually write one constructor that fully initializes the object; if there are others, they all call this(...) with appropriate defaults.
An object should be 100% initialized and ready for use when it's created.
Some frameworks, for example Hibernate, demand a no-arg constructor. The way they clash with best practices makes me uneasy sometimes.
Having a default and empty (blank) constructor prevents you from having any final fields. This leads to a lot of mutability where there it is often not needed.
The builder pattern allows you to mix these two styles and allow more flexible initialization while still having immutability by hiding a many-arg constructor behind the factory.
For some POJO classes or simple class, default constructor is useful when you sometimes want to do unit testing on the class using them. You don't need to mock them, you can new an object with default constructor and test the value set and get from them or pass them as an argument.
You want to create a blank constructor for the classes that extended this
class and since it has been extended the class... the child now has super which references the class above it it's parent. In the event the child did not specify super(stuff)... the stuff inside to reference the other constructors to use it will now attempt to reference the empty constructor.
I'm not sure what the error will be I am coding my first parent object relationship now and was looking up things here ha cheers.
I guess I should add the moment you make a constructor that isn't the empty one you lose the default empty one so now super() which is default in the extended class won't have something to point to. Of course if you created the extended classes to take care of super by specifying on which gets rid of the default super() then you sidestep this but what if someone wants to use your class and extend from it and didn't realize there isn't an empty set when you could have
just created one.
This is my first post but wanted to take a crack from how I understand it.