Java 当响应体根据程序中的if条件发生变化时,如何处理响应体?
我想正确地操纵响应体,但我觉得我做得不对,看看我的响应类:Java 当响应体根据程序中的if条件发生变化时,如何处理响应体?,java,Java,我想正确地操纵响应体,但我觉得我做得不对,看看我的响应类: public final class Response { public static String body; private static int statusCode; private Response() {} public static APIGatewayProxyResponseEvent response() { assignStatusCode();
public final class Response {
public static String body;
private static int statusCode;
private Response() {}
public static APIGatewayProxyResponseEvent response() {
assignStatusCode();
return new APIGatewayProxyResponseEvent()
.withStatusCode(statusCode)
.withBody(body);
}
private static void assignStatusCode() {
switch (body) {
case INVALID_REQUEST_BODY:
case NULL_REQUEST_BODY:
statusCode = STATUS_400;
break;
case INVALID_EMPLOYEE_DATA:
case ALREADY_EMPLOYED:
case EMPLOYEE_SAVED:
statusCode = STATUS_200;
break;
default:
throw new IllegalArgumentException(UNKNOWN_RESPONSE_BODY);
}
}
}
像INVALID_REQUEST_BODY这样的情况只是在其他类中定义的字符串。我有一个程序,在这个程序的最后,我想返回一个带有相应响应主体和状态代码的响应。这个项目要大得多,但我的意思是:
public static void main(String[] args) {
//some code
public boolean isShiftPossible (Shift shift){
if (!isShiftDateTimeValid(shift)) {
Response.body = INVALID_DATE_TIME;
} else if (isShiftAlreadyPlanned(shift)) {
Response.body = SHIFT_EXISTS;
} else {
Response.body = SHIFT_SAVED;
return true;
}
return false;
}
//some code
return response();
}
此外,我从Sonarint收到以下警告:实例方法不应写入“静态”字段
我知道这个警告意味着什么,但我不想让我的方法成为静态的。如何正确设计响应主体管理?将
响应
中的字段设置为静态
将在处理同时请求时引发问题
假设request1和request2几乎同时收到。request1将响应正文
设置为SHIFT\u SAVED
,并且在返回请求1的响应之前,request2将响应正文
设置为无效日期时间
在这种情况下,对这两个请求的响应将是无效的日期时间。
因此,每个请求都应该有一个单独的响应
根据您在问题中的评论,如果有多个类处理特定请求,则在删除响应中主体
和状态码
的静态
后,执行类似于以下伪代码的操作
ClassOne {
handleRequest(Request request) {
// First method that handles the request creates the response object
// which is then passed on to the other classes.
Response response = new Response();
ClassTwo two = new ClassTwo();
two.handleRequest(request,response);
}
}
ClassTwo {
handleRequest(Request request, Response response) {
ClassThree three = new ClassThree();
boolean value = two.handleRequest(request,response);
// do some process with value
// update body of response
}
}
ClassThree {
boolean handleRequest(Request request, Response response) {
response.body = some_value;
// do the processing.. update response
return true;
}
}
为什么您在响应中将正文
和状态码
声明为静态
?@GauthamM,因为我想从不同的包中自由访问这些静态字段,而无需实例化此类。如果它们不是静态的,我每次都必须创建一个响应类对象,并从每个方法返回它,以便其他类可以看到设置了什么ResponseBy。您的响应类不是表示对单个请求的响应吗?是的,但假设我有20个类,在这些类的每个方法中,如果条件改变了我的ResponseBy字段,我就有了。那么如何设计响应类呢?假设您有3个类,那么:class1
method调用class2
method,class2
method将调用class3
method。现在,class3方法将创建一个响应对象并将其返回到class2
,该对象在自身更新后将其返回到class1
。20节课也差不多吧?好吧,现在我明白你的意思了,谢谢