简体   繁体   中英

how to design class method that returns two different return type?

一个具有较小逻辑的子类,它返回布尔值true / false或错误消息,但在发生任何异常的情况下,它会陷入同一个类和错误消息中,仅是为了暗示上层类,该上层类曾在UI中显示错误消息。无法考虑如何管理子类的返回值,因为如果子类成功运行,则返回布尔值true / false,但是如果出错,则返回String错误消息,这一点我发现方法有两种不同类型的返回值问题。帮助我如何解决这个问题。

You have two options return an object

class Status {
   Boolean succesful;
   String errorText;
}

or throw an Exception if an error occurs

throw new Exception( errorText );

Why do you return String error code? Just throw your exception(maybe, wrapped in some other one) and receive it upper.

Your question is not very clear.
From my understanding, you should return a Boolean or an Exception.
You should set your error message in the exception (see: http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Exception.html#Exception%28java.lang.String%29 ). You can also return different exceptions if you need.

If you have your subclass return a variable of type Object you can check its data type higher up.

//Success
Object object = new Boolean();

//Fail
Object object = new String();

if(object instanceOf Boolean) {
//Do something
} else if(object instanceOf String) {
//Do something else
}

Consider using Functional Java's Either class. It is an implementation to hold one of two values.

Either

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM