我有一个名为handleImageBannerUpload的方法。在这个方法中,我有一个switch语句。有3个switch case,每个都应该返回一个不同的ResponseEntity:
switch(type){
case "localEvent":
try {
LocalEvent localEvent = localEventRepository.findOne(id);
storageService.store(file, localEvent);
String path = localEvent.getBannerPath();
log("FileUploadController: " + path);
result = ResponseEntity
.ok()
.header(HttpHeaders.CONTENT_TYPE, "application/json;")
.body(path);
}
catch (StorageException e) {
result = ResponseEntity
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.header(HttpHeaders.CONTENT_TYPE, "application/json;")
.body("\"" + e.getMessage() + "\"");
}
case "session":
try {
Session session = sessionRepository.findOne(id);
storageService.store(file, session);
String path = session.getSessionDescriptionImagePath();
log("FileUploadController: " + path);
result = ResponseEntity
.ok()
.header(HttpHeaders.CONTENT_TYPE, "application/json;")
.body(path);
}
catch (StorageException e) {
result = ResponseEntity
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.header(HttpHeaders.CONTENT_TYPE, "application/json;")
.body("\"" + e.getMessage() + "\"");
}
case "theme":
try{
Theme theme = themeRepository.findOne(id);
storageService.store(file, theme);
String path = theme.getThemeImagePath();
log("FileUploadController: " + path);
result = ResponseEntity
.ok()
.header(HttpHeaders.CONTENT_TYPE, "application/json;")
.body(path);
}
catch (StorageException e) {
result = ResponseEntity
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.header(HttpHeaders.CONTENT_TYPE, "application/json;")
.body("\"" + e.getMessage() + "\"");
}
}
return result;
如何创建一个可以在switch语句中返回ResponseEntity的正确result
变量?
答案 0 :(得分:0)
你的设计气味已渗透到你的代码中。你正在牺牲清晰度,可读性和可测试性而转向支持。
您需要的是3个简明的终点:
POST /banner/event
POST /banner/theme
POST /banner/template
从那里你应该遵守单一责任原则,以便每个相应的控制器方法简洁明了。