首页 > java 中如何处理设计一个方法

java 中如何处理设计一个方法

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.


使用哪种不重要,重要的是选择了一种就要作为惯例遵守(书上读到的)


对于增删改操作的返回值,没有什么通用的方法,可以考虑使用泛型。
比如和MySQL通信时增删改操作的返回值可以为int以表示受影响行数。
如果是其他的,比如Redis:

另外,也需要考虑返回值是否会对客户端代码造成困扰。


Object addObject(Object obj);
Object delObject(Object obj);
Object modifyObject(Object obj);

像这种方式比较适合做串式操作。方法返回后还可以利用返回对象做一些数据处理。其他两种完全就是标志本次操作是否成功,
返回int类型可以表示的错误类型会多一点,也就是说提示错误粒度更加细。
boolean类型就两种,要么成功要么失败,提示错误粒度略粗。
还是要看你具体业务了

【热门文章】
【热门文章】