Reputation: 871
I was reading an open-source code, and there was a constructor designed like this:
public class FeatureSequence2FeatureVector extends Pipe implements Serializable
{
boolean binary;
public FeatureSequence2FeatureVector (boolean binary)
{
this.binary = binary;
}
public FeatureSequence2FeatureVector ()
{
this (false);
}
}
This may be just a trivial preference matter, but what I would do is like this:
public class FeatureSequence2FeatureVector extends Pipe implements Serializable
{
boolean binary = false;
public FeatureSequence2FeatureVector (boolean binary)
{
this.binary = binary;
}
public FeatureSequence2FeatureVector ()
{
}
}
Is there any possible negative outcome by assigning an initial value for class variables? Would the two ways be almost equally preferred?
Upvotes: 3
Views: 131
Reputation: 96394
These two ways are not equally preferred.
The original way makes sure that all initialization goes through a primary constructor. The second way allows different paths for initializing an object.
In your example it's pretty trivial. But with the second way one constructor could be modified to do something different from how the other constructor did things, whereupon how your objects are initialized depends on which constructor was chosen.
This question shows a situation where allowing different paths caused trouble.
Upvotes: 4
Reputation: 15103
One reason I've seen developers do this is for maintainability and future-proofing.
Let's break it down into a different application:
public void foo() {
this.foo(1);
}
public void foo(int a) {
this.foo(a, 2, 3);
}
public void foo(int a, int b, int c) {
// ...
}
foo
is assumed to do the exact, or a similar, operation - regardless of the overload. However, what if that functionality were to change? In your example, you'd have to change the functionality for both versions, whereas in the above example, only foo(int, int, int)
would have to be changed.
Future-proofing is something that is taken into account in the design of an API, and the above design pattern is adopted frequently due to the ability to maintain one block of code versus 2 or 3 (or however many overloads you have).
Constructors are no different, other than that they are invoked with this(...)
.
Upvotes: 1