在Java中检查非空的其他方式

huangapple go评论93阅读模式
英文:

Other ways to check for not null in Java

问题

我在项目中有很多这种类型的代码:

if (entityRepository.saveEntity(new RemoteEntityBuilder()
   .appId(appId)
   .nameSpace(nameSpace)
   .entityType(entityType)
   .entityId(entityId)
   .blobs(Lists.list(new RemoteBlobBuilder()
      .blobName(blobName)
      .blobStream(new SimpleRemoteInputStream(inputStream))
      .build()))
   .build()) != null) {  
   // 表示实体已保存
} else {
   // 表示实体未保存
}

saveEntity 方法返回 NULL(如果操作失败)或者如果操作成功则返回被保存的对象/实体。我的问题是,是否有更好的方式来表示此代码,例如使用 != null

if (entityRepository.saveEntity(...)) {
}

或者其他方式。

更新:

saveEntity 方法如下:

  @Override
  public RemoteEntity saveEntity(RemoteEntity entity)
      throws NotBoundException, RemoteException {
    RemoteEntities remoteEntities = saveEntities(new RemoteEntity[] {entity});
    return remoteEntities != null ? remoteEntities.entities().stream().findFirst().get() : null;
  }

经过 YCF_L 的建议,代码现在如下:

entityRepository.saveEntity(new RemoteEntityBuilder()
    .appId(appId)
    .nameSpace(nameSpace)
    .entityType(entityType)
    .entityId(entityId)
    .blobs(Lists.list(new RemoteBlobBuilder()
        .blobName(blobName)
        .blobStream(new SimpleRemoteInputStream(inputStream))
        .build()))
    .build()).ifPresentOrElse(remoteEntity -> {
      pubSubService.updated(remoteEntity.appId(), remoteEntity.nameSpace(),
          remoteEntity.entityType(), remoteEntity.entityId());
      setStatus(Status.SUCCESS_CREATED);
    }, () -> {
      setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
    });

在集成开发环境中的显示如下(对我来说看起来非常整洁):

在Java中检查非空的其他方式

英文:

I have a lot of this kind of code in my project:

if (entityRepository.saveEntity(new RemoteEntityBuilder()
   .appId(appId)
   .nameSpace(nameSpace)
   .entityType(entityType)
   .entityId(entityId)
   .blobs(Lists.list(new RemoteBlobBuilder()
      .blobName(blobName)
      .blobStream(new SimpleRemoteInputStream(inputStream))
      .build()))
   .build()) != null) {  
   // Meaning entity was saved
} else {
   // Meaning entity was not saved
}

The saveEntity method returns either NULL (if operation failed) or the object/entity that was saved if the operation was successful. My question is, is there a better way to represent this code with the use of != null for instance:

if(entityRepository.saveEntity(...)) {
}

Or something else.

UPDATE:

The saveEntity method is this

  @Override public RemoteEntity saveEntity(RemoteEntity entity)
      throws NotBoundException, RemoteException {
    RemoteEntities remoteEntities = saveEntities(new RemoteEntity[] {entity});
    return remoteEntities != null ? remoteEntities.entities().stream().findFirst().get() : null;
  }

Here's how it looks now thanks to YCF_L:

  entityRepository.saveEntity(new RemoteEntityBuilder()
                .appId(appId)
                .nameSpace(nameSpace)
                .entityType(entityType)
                .entityId(entityId)
                .blobs(Lists.list(new RemoteBlobBuilder()
                    .blobName(blobName)
                    .blobStream(new SimpleRemoteInputStream(inputStream))
                    .build()))
                .build()).ifPresentOrElse(remoteEntity -> {
              pubSubService.updated(remoteEntity.appId(), remoteEntity.nameSpace(),
                  remoteEntity.entityType(), remoteEntity.entityId());
              setStatus(Status.SUCCESS_CREATED);
            }, () -> {
              setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
            });

Here's how the code looks in the IDE (looks pretty clean to me):

在Java中检查非空的其他方式

答案1

得分: 4

我会在你的情况下使用Optional

public Optional<RemoteEntity> saveEntity(RemoteEntity entity) throws NotBoundException, RemoteException {
    RemoteEntities remoteEntities = saveEntities(new RemoteEntity[]{entity});
    return remoteEntities.entities().stream()
            .findFirst();
}

然后:

if(entityRepository.saveEntity(...).isPresent()) {
   ...       
}

实际上,对于Optional,你有很多选择,你也可以使用ifPresent

entityRepository.saveEntity(...)
    .ifPresent(r -> ..)

或者抛出异常:

entityRepository.saveEntity(...)
    .orElseThrow(() -> ..)
英文:

I would use Optional in your case :

public Optional&lt;RemoteEntity&gt; saveEntity(RemoteEntity entity) throws NotBoundException, RemoteException {
    RemoteEntities remoteEntities = saveEntities(new RemoteEntity[]{entity});
    return remoteEntities.entities().stream()
            .findFirst();
}

and then :

if(entityRepository.saveEntity(...).isPresent()) {
   ...       
}

In fact you have many choices with Optional, you can use ifPresent also :

entityRepository.saveEntity(...)
    .ifPresent(r -&gt; ..)

Or throw an exception:

entityRepository.saveEntity(...)
    .orElseThrow(() -&gt; ..)

答案2

得分: 1

"更好"可能是个人观点问题。

根据你的示例,实现这一目标的方法是创建另一个调用 saveEntity() 并返回 truefalse 的方法。(我不禁在想,如果 saveEntity() 的操作失败了,为什么不抛出异常 — 在我看来,这样更正常。)

如果你只是不喜欢很难找到比较部分,你可以颠倒顺序:

if (null != entityRepository.saveEntity(...))

根据我的经验,我可能会将调用完全移到条件之外,因为我发现在条件中使用副作用可能会令人困惑。

RemoteEntity myEntity = entityRepository.saveEntity(...)
if (myEntity != null) ...
英文:

What is "better" may be a matter of opinion.

Given your example, the way to achieve that would be to create another method that calls saveEntity() and returns true or false. (I do wonder why saveEntity() doesn't throw an exception if its operations fails -- that would be more normal in my experience.)

If you simply don't like that the comparison is hard to spot, you might reverse the order:

if (null != entityRepository.saveEntity(...))

I would probably move the call outside of the if entirely, as I find side effects in conditionals potentially confusing.

RemoteEntity myEntity = entityRepository.saveEntity(...)
if (myEntity != null) ...

huangapple
  • 本文由 发表于 2020年10月21日 00:44:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/64449682.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定