这里有新手..我想知道在下列情况下最佳做法是什么:
我使用MVC模式。我的Controller类需要调用Model类来执行一个过程。此过程有4个步骤。在前面的3个步骤中,如果出现问题,模型将生成一个字符串列表,除了出现错误消息之外,控制器必须确保向用户显示这些字符串。在最后一步中,模型将生成一个Map,Controller必须再次确保向用户显示。在最后一步中,也可能发生超时..
处理此问题的最佳方法是什么?
我在下面提出了两个粗略的建议草案。
备选方案1:
public class Model{
public List<String> step1(){
// return empty list if ok, fill list otherwise
}
public List<String> step2(){ // return empty list if ok, fill list otherwise}
public Map<String, String> step3(){ // return empty list if ok, fill list otherwise}
}
public class Controller{
Model myMOdel;
public void doProcedure(){
List<String> list = myModel.step1();
if(list.size() != 0){
String errormessage = "Step 1 error message"
// make sure View display list and errormessage
return;
}
list = myModel.step2();
if(list.size() != 0){
String errormessage = "Step 2 error message"
// make sure View display list and errormessage
return;
}
Map<String, String> map = myModel.step3();
if(map.size()!=0){
String errormessage = "Step 3 error message"
// make sure View display map and errormessage
return;
}
// make View display "procedure ok" message to user
}
我不喜欢的是,它打开了控制器忘记执行某个步骤或以错误的顺序执行步骤的可能性。
备选方案2:
public class Model {
final static int STEP1_ERROR;
final static int STEP2_ERROR;
final static int STEP3_ERROR;
private void step1() throws ModelException{
List<String> list;
if(somethingwentwrong){
throw new ModelException(STEP1_ERROR, "errormessage for step1", list)
}
}
private void step2() throws ModelException {.
List<String> list;
if(somethingwentwrong){
throw new ModelException(STEP2_ERROR, "errormessage for step2", list)
}
}
private void step3() throws ModelException{.
Map<String, string> map;
if(somethingwentwrong){
throw new ModelException(STEP3_ERROR, "errormessage for step3", map)
}
}
public void procedure() throws ModelException{
step1();
step2();
step3();
}
}
public class Controller{
Model myModel;
try{
model.procedure();
}
catch(ModelException e){
switch(e.getErrorNum){
case // handle error type 1
case // handle error type 2 etc
}
}
}
public class ModelException extends Exception{
List<String> list;
Map<String, String> map;
int errorNum;
public ModelException(int errorNum, String message, List<String>){
....
}
public ModelException(int errorNum, String message, Map<String><String>){
....
}
}
答案 0 :(得分:0)
第二种选择肯定更好。但你甚至可以通过用适当的异常层次结构替换errorNum字段来改进它(因为每个异常类型应描述执行中的特定条件):
public class ModelException extends Exception{}
public class Step1ModelException extends ModelException{
public Step1ModelException(List<String> details) {...}
public List<String> getDetail(){...}
}
public class Step2ModelException extends ModelException{
public Step2ModelException(List<String> details) {...}
public List<String> getDetail(){...}
}
public class Step3ModelException extends ModelException{
public Step3ModelException(Map<String,String> details) {...}
public Map<String,String> getDetail(){...}
}