Reputation: 11669
Below is my response object which I use to construct a response and send it back to caller as I have a system which is on request/response pattern.
public class DataResponse {
private String response;
private DataErrorEnum error;
private DataStatusEnum status;
public DataResponse(String response, DataErrorEnum error, DataStatusEnum status) {
this.response = response;
this.error = error;
this.status = status;
}
public String getResponse() {
return this.response;
}
public DataErrorEnum getError() {
return this.error;
}
public DataStatusEnum getStatus() {
return this.status;
}
}
Now some times in my application code, I am creating response object like this:
new DataResponse(null, errorEnum, statusEnum);
As you can see I am explicitly setting null
which is ok but sometimes it cause confusion that which field is null so I decided to create another constructor in DataResponse class like this:
public class DataResponse {
private String response;
private DataErrorEnum error;
private DataStatusEnum status;
public DataResponse(String response, DataErrorEnum error, DataStatusEnum status) {
this.response = response;
this.error = error;
this.status = status;
}
// new constructor
public DataResponse(DataErrorEnum error, DataStatusEnum status) {
this.response = null;
this.error = error;
this.status = status;
}
public String getResponse() {
return this.response;
}
public DataErrorEnum getError() {
return this.error;
}
public DataStatusEnum getStatus() {
return this.status;
}
}
So that I can create object now like this: By this, I don't need to send null response since that is by default in my other constructor.
new DataResponse(errorEnum, statusEnum);
Now my question is - Is there any way I can combine both of my constructor into one? Or I need to have two constructor for this always?
Upvotes: 1
Views: 78
Reputation: 1132
If response is always null then the second constructor holds good. Both the constructor are doing similar functionality. Its better to have one constructor for better readability of code.
Upvotes: 0
Reputation: 8657
You can't combine both constructors into one.
But you can declare main constructor that construct your fields, and the other constructors just call it, for example.
// new constructor
public DataResponse(DataErrorEnum error, DataStatusEnum status) {
this(null, error, status);
}
public DataResponse(String response, DataErrorEnum error, DataStatusEnum status) {
this.response = response;
this.error = error;
this.status = status;
}
Upvotes: 7