多层循环方法状态的返回tip

多层循环方法状态的返回技巧:

业务中业务代码较多,抽象出方法方便复用,但多层循环的返回状态不好确认,经老大提点,使用 ResultMsg对象, 01位与的结果来向上返回状态,循环处理状态;

来段代码解读下,show code ~~:

public class ForReturn {

public static final int ZREO = 0;
public static final int ONE = 1;

/*
* ResultMsg [code=0, msg=/ by zero] ----------------
* 0 & 0 = 0
* 0 & 1 = 0
* 1 & 0 = 0
* 1 & 1 = 1
*/

public static void main(String[] args) {
System.out.println(for1());
System.out.println("----------------");
OneBitAndZero();
}

public static void OneBitAndZero() {
int zz = 0 & 0;
int zo = 0 & 1;
int oz = 1 & 0;
int oo = 1 & 1;
System.out.println("0 & 0 = " + zz);
System.out.println("0 & 1 = " + zo);
System.out.println("1 & 0 = " + oz);
System.out.println("1 & 1 = " + oo);
}

public static ResultMsg for1() {

int code = ONE;
String msg = "";// 仅返回错误信息,在得到最后的结果状态后加入正确描述信息,方便处理
for (int i = 0; i < 5; i++) {
ResultMsg resultMsg = for2(i);
code = code & resultMsg.getCode();
msg += resultMsg.getMsg();
}
return new ResultMsg(code, msg);
}

private static ResultMsg for2(int i) {
int code = ONE;
String msg = "";
try {
int re = 5 / (i - 2);
} catch (Exception e) {
code = ZREO;
msg = e.getMessage();
}
return new ResultMsg(code, msg);
}

}

class ResultMsg {
private int code;
private String msg;

public ResultMsg(int code, String msg) {
super();
this.code = code;
this.msg = msg;
}

public int getCode() {
return code;
}

public void setCode(int code) {
this.code = code;
}

public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}

@Override
public String toString() {
return "ResultMsg [code=" + code + ", msg=" + msg + "]";
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值