正常情况下,在Java中入参是不建议用做返回值的。除了造成代码不易理解、语义不清等问题外,可能还埋下了陷阱等你入坑。
问题背景
比如有这么一段代码:
@Named
public class AService {
private SupplyAssignment localSupply = new SupplyAssignment();
@Inject
private BService bervice;
public List<Supply> calcSupplyAssignment()
List<Supply> supplyList = bService.getLocalSupplyList(this.localSupply);
…
return supplyList;
}
}
上面代码,服务A希望调用服务B,以获取supplyList,但同时,服务A又希望修改localSupply的状态值,未能避免修改calcSupplyAssignment接口的(不想改返回的类型),将localSupply作为了入参但同时也用作了返回值。
服务B代码如下:
@Named
public class BService {
public List<Supply> getLocalSupplyList (SupplyAssignment localSupply)
SupplyAssignment supplyAssignment = this.getSupplyAssignment();
// 希望localSupply被重新赋值后返回
localSupply = supplyAssignment;
…