Here is a json which comes in the request param. I am constructing a class with getter and setter for accessing the values in json so that I could be able to pass the class object to different methods and able to access the member variables in them.
public class RequestParams {
private String student_id;
private String student_name;
private String student_role_number;
private String department_name;
private String stream;
private JSONObject studentDetails;
public RequestParams(HttpServletRequest request) {
this.studentDetails = request.getParameter(“studentdetails”);
}
public String getStudentId() {
if(this.student_id == null) {
this.setStudentId();
}
return this.student_id;
}
public String getStudentName() {
if(this.student_name == null) {
this.setStudentName();
}
return this.student_name;
}
public String getRoleNumber() {
if(this.student_role_number == null) {
this.setRoleNumber();
}
return this.student_role_number;
}
public String getDepartmentName() {
if(this.department_name == null) {
this.setDepartmentName();
}
return this.student_name;
}
public String getStream() {
if(this.stream == null) {
this.setStream();
}
return this.stream;
}
public void setStudentId() {
this.student_id = this.studentDetails.getString("student_id");
}
public void setStudentName() {
this.student_name = this.studentDetails.getString("student_name");
}
public void setRoleNumber() {
this.student_role_number = this.studentDetails.getString("role_number");
}
public void setDepartmentName() {
this.department_name = this.studentDetails.getString("department_name");
}
public void setStream() {
this.stream = this.studentDetails.getString("stream");
}
}
Have the following doubts,
- Constructing as class object to reference it from different methods - Is this a good one? Am I going wrong?
- How to organise my getter setter so that only set is called only for the first time and for the next calls the value is returned directly? Is there a better way to avoid the null check each time
if(this.student_id == null) {
this.setStudentId();
}
PS: I could not invoke all the setter initially from the constructor because all the values declared in the class need not be necessarily present in the json. So, I thought that it would be better if I could initialise the member variable with value during first access.
Aucun commentaire:
Enregistrer un commentaire