java 中我们很常见的设计 API 的例子是对一个对象进行增, 删, 查,改.
比如
Object addObject(Object obj);
Object delObject(Object obj);
Object modifyObject(Object obj);
成功返回 obj, 不成功(参数不合法,或已经存在, 或不存在)抛出异常
还是
int addObject(Object obj);
int delObject(Object obj);
int modifyObject(Object obj);
如果成功返回 0, 不成功, 返回其他数字
还是
boolean addObject(Object obj);
boolean delObject(Object obj);
boolean modifyObject(Object obj);
如果成功返回 0, 不成功(参数不合法,或已经存在, 或不存在), 抛出异常
感谢各位热心回答, 我已经决定采用第一种方式了.原因: 1. 性能不是那么的关键; 2
绝大多数我们认为参数是正确的.排除异常较返回 Errorcode 让代码更加简洁.
补充: 以下是从 这里 找到的一个回答, 基本决定采用第一中方式, 这或许是 java 语言本
身的特点, 如果是 c 或 cpp 我更倾向于第二种方式.
Exceptions impose quite an overhead on the runtime performance, but makes reasoning about the program flow drastically easier. This reduces faulty programming (semantic errors), especially as it forces you to deal with them - they 'fail securely' by terminating the program if they are ignored. They are ideal for 'situations which are not supposed to happen'. Also they can transport metadata like a stacktrace.
Error codes, on the other hand, are light-weight, fast, but forces the method caller to explicitely check them. Failure to do so often results in program flaws, which can range from silent data corruption, security holes, to nice fireworks if your program happens to be running inside a space rocket.