Check constructor to return a valid link
I am using Java 1.7.0_79
The code in the questions is this and I instantiate a new object and I want to check if the object has a valid reference after the constructor returns, I check if it is null:
mClientConnection = null;
mClientConnection = new XMPPTCPConnection(configBuilder.build());
if(mClientConnection == null) {
return false;
}
The constructor implementation contains the following:
public XMPPTCPConnection(XMPPTCPConnectionConfiguration config) {
super(config);
this.config = config;
}
I'm wondering how can I check that the mClientConnection contains a valid link?
I am using findbugs and I am getting this reported error:
This method contains a redundant check for a known non-zero value against the constant null
source to share
It is not a constructor that returns a newly created object. The constructor does not return anything - it has no return type and no instruction return
.
When you create a new object using a statement new
, the Java runtime will allocate memory for the object and initialize it by calling the appropriate constructor. The operator then new
returns a reference to the object, not the constructor.
The operator new
never returns null
, so you never need to check if the link is null
right after use new
.
source to share
If you want to validate, you need to add a method that does this.
mClientConnection = new XMPPTCPConnection(configBuilder.build());
if (!mClientConnection.isValid())
return false;
Which makes the actual component dependent on what it is and does, and you can write that in a method.
Once you set the value of a variable from an object new
, you can assume that it is not null
(unless you are setting it in null
a different thread)
source to share