I'm working with RxJava and I don't know where the right place to check arguments would be. For example, say I have the following:
public Completable createDirectory(final String path) {
return Completable.create(emitter -> {
final File directory = new File(path);
final boolean createdSuccessfully = directory.mkDirs();
if (createdSuccessfully) {
emitter.onComplete();
} else {
emitter.onError(new IOException("Failed to create directory.");
}
}
}
Would it be better to check for a null path in the root of the method, or at the start of the completable? I'm leaning towards the former, but I'm interested in the pros and cons of both approaches.
答案 0 :(得分:0)
我会说:这取决于你想要实现的目标。
如果在completeable.create之前检查方法入口的空值,则会在调用线程上抛出NPE / IllegalArgumentException。这将遵循“快速失败”的理念。可能的优点: *在方法调用上快速失败 *调用线程的callstack中的异常
如果您签入Completable.create-lambda,将在lambda-evaluation(订阅)上调用它。
示例:在调用线程上调用createDirectory-Method,添加subscribeOn和subscribe:订阅时将在subscribeOn-Scheduler-Thread上抛出NPE / IllegalArgumentException。
只有在您订阅返回的Completable时才会抛出它。也许你创建一个Completable但从不订阅它。然后就不会抛出任何异常。这可能是检查lambda的专业人士。如果你不检查,那么无论如何都会在subscribeOn线程上抛出NPE。在subscribeOn线程上抛出的异常可能是否定的,因为您只看到subscribedOn-thread的跟踪。有时在仅使用callstack切换线程时,不容易看到流程。您不会看到调用了createDirectory方法。你只会看到lambda调用加上一些反应堆栈压缩。
我想说:如果您订阅了某个时刻创建的Completable,请快速使用fail。如果可能的话,任何时候都没有订阅创建的Completable,它可能会使用一些Precondition和一条消息,因为它只会在订阅时抛出(lazy)。无论如何,如果你检查对象#requireNonNull()而没有lambda中的任何消息,你可以放弃检查null,因为无论如何都会抛出NPE。