我最近剛開始作為一名開發人員,但我仍然在為撰寫代碼的方式而苦苦掙扎。
有沒有更好的方法來撰寫這兩個 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 中。
uj5u.com熱心網友回復:
看起來您不關心item.getContentModificationOnly()第二個 if 陳述句中的 true 或 false ,因為您的代碼是(Boolean.TRUE.equals(item.getContentModificationOnly()) || Boolean.FALSE.equals(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");
}
uj5u.com熱心網友回復:
首先如果條件
if (item.getContentModificationOnly() && !force) {
第二個If條件
if ((item.getContentModificationOnly() || !item.getContentModificationOnly()) && force) {
下面的代碼將始終回傳 true
(item.getContentModificationOnly() || !item.getContentModificationOnly())
所以修改第二個 if stmnt 到 just
if (force){
uj5u.com熱心網友回復:
取決于回傳型別item.getContentModificationOnly()。如果它是布爾值,則第二條陳述句可以簡化為
if(item.getContentModificationOnly() != null && force)
如果回傳型別item.getContentModificationOnly()是布爾型,那么陳述句可以簡化為
if(force)
以及上面@LiLittleCat 的答案(如果正確)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/524680.html
標籤:爪哇春天弹簧靴逻辑
上一篇:如何識別服務器端的唯一客戶端?
