[英]How to combine two methods with different return type but same body with throw statement?
I have two methods with different data types, but with same body.我有两种具有不同数据类型但具有相同主体的方法。 I'm not using any
return
.我没有使用任何
return
。 I'm using these methods for throwing exceptions only.我使用这些方法仅用于抛出异常。 Is there any way to combine these two methods or any way to optimize the code?
有没有什么办法可以结合这两种方法或者有什么方法可以优化代码?
public MyDataType1 method1(MyArg arg){
/* some logic */
throw new CustomException();
}
public MyDataType2 method2(MyArg arg){
/* some logic, same as above method logic*/
throw new CustomException();
}
PS: I don't want to use interface or some new method with common logic. PS:我不想使用接口或一些具有通用逻辑的新方法。
Use an interface to make compatible使用接口使兼容
interface DataType{
}
class MyDataType1 implements DataType{
}
class MyDataType2 implements DataType{
}
You'll be able to你将能够
public DataType method1(MyArg arg){
/* some logic */
throw new CustomException();
}
It is a little-known language feature called a 'method' :)这是一个鲜为人知的语言功能,称为“方法”:)
public MyDataType1 method1(MyArg arg){
logic();
throw new CustomException();
}
public MyDataType2 method2(MyArg arg){
logic();
throw new CustomException();
}
private void logic() {
/* some logic */
}
I have two methods with different data types, but with same body.我有两种方法,它们的数据类型不同,但正文相同。 I'm not using any
return
.我没有使用任何
return
。 I'm using these methods for throwing exceptions only.我正在使用这些方法仅引发异常。 Is there any way to combine these two methods or any way to optimize the code?
有什么方法可以将这两种方法结合起来,也可以通过什么方法来优化代码?
public MyDataType1 method1(MyArg arg){
/* some logic */
throw new CustomException();
}
public MyDataType2 method2(MyArg arg){
/* some logic, same as above method logic*/
throw new CustomException();
}
PS: I don't want to use interface or some new method with common logic. PS:我不想使用具有通用逻辑的界面或某些新方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.