在 CRUD 中执行 C 的方法中,它应该返回什么?

Jac*_*ine 2 java oop api

想象一个具有创建Address类型对象的方法的接口。此处涉及的实体无关紧要。

/**
 * @throws IllegalArgumentException if addy is null or invalid
 * @throws PersistenceException if db layer encounters a problem
 */
Object addAddress( Address addy );
Run Code Online (Sandbox Code Playgroud)

addAddress将域对象插入到数据库中。

我将返回值保留为Object。我的问题是:返回类型应该是什么?通常我选择了一个布尔返回值(假设没有抛出异常)。有时我选择返回Address记录的自动生成的 PK 密钥。通常情况下,我只是将其保留为void。你通常做什么以及为什么?

Fre*_*örk 5

我传统上使用这种方法返回生成的 id 或根本没有返回值。但我开始喜欢返回添加的对象本身的想法,填充生成的 PK。如果对象有方法,您可以使用返回值并直接调用其上的方法,或者您可以直接将其传递给其他方法:

// invoke a method on the returned object
addAddress(theAddress).DoSomething();

// pass the object to some other method
SomeOtherMethod(addAddress(theAddress));
Run Code Online (Sandbox Code Playgroud)

我不会做的是使用布尔值;add 方法中的失败是一种异常状态,应该被视为异常状态,抛出异常。