Spring Boot 有没有更好的方法来编写这个if语句?

qv7cva1a  于 2022-11-05  发布在  Spring
关注(0)|答案(3)|浏览(217)

我最近开始作为一个开发人员,我仍然在努力与我写代码的方式有点。
有没有更好的方法来写这两个if语句?你会怎么写?为什么?
Java程式码:

@Override
@Transactional
public void deleteItem(final ConfigurationType type, final long itemId, final boolean force) {
    this.applicationNameUtils.throwOnInvalidApplication(type.getApplication());
    final ConfigurationItemModel item =
        this.configurationItemRepository.findByApplicationAndTopicAndId(type.getApplication(), type.getTopic(), itemId)
            .orElseThrow(() -> new ResourceNotFoundException(itemId, "Configuration Item"));
    if (Boolean.TRUE.equals(item.getContentModificationOnly()) && Boolean.FALSE.equals(force)) {
        throw new ContentModificationOnlyException("Configuration Item cannot be deleted");
    }
    if ((Boolean.TRUE.equals(item.getContentModificationOnly()) || Boolean.FALSE.equals(item.getContentModificationOnly())) && Boolean.TRUE.equals(force)) {
        this.assignmentService.deleteAssignmentsByItem(item);
        this.configurationInstanceRepository.deleteByItem(item);
        this.configurationItemRepository.deleteById(itemId);
    }
}

我不确定我是否能以某种方式在if-else中将这两者结合起来。

6qfn3psc

6qfn3psc1#

因为你的代码是(Boolean.TRUE.equals(item.getContentModificationOnly()) || Boolean.FALSE.equals(item.getContentModificationOnly()),所以看起来你并不关心第二个if语句中的item.getContentModificationOnly()是真还是假。所以如果你的逻辑是正确的,我建议你这样编写代码:

if (fore) {
    this.assignmentService.deleteAssignmentsByItem(item);
    this.configurationInstanceRepository.deleteByItem(item);
    this.configurationItemRepository.deleteById(itemId);
} else if (Boolean.TRUE.equals(item.getContentModificationOnly()) {
    throw new ContentModificationOnlyException("Configuration Item cannot be deleted");
}
yks3o0rb

yks3o0rb2#

第一个if条件

if (item.getContentModificationOnly() && !force) {

第二个If条件

if ((item.getContentModificationOnly() || !item.getContentModificationOnly()) && force) {

下面的代码将始终返回true

(item.getContentModificationOnly() || !item.getContentModificationOnly())

因此将second if stmnt修改为仅
一个月一个月{

eufgjt7s

eufgjt7s3#

取决于返回类型item.getContentModificationOnly()。如果它是Boolan,那么第二条语句可以简化为

if(item.getContentModificationOnly() != null && force)

如果item.getContentModificationOnly()的返回类型为Bolean,则该语句可以简化为

if(force)

和上面的@LiLittleCat的答案(如果正确)。

相关问题