簡體   English   中英

FindBugs死店警告 - 我應該重組代碼還是忽略警告

[英]FindBugs Dead Store Warning - Should I restructure code or Ignore Warning

我在下面的int i上用Findbugs收到DeadStore警告。 由於可讀性,我不想寫單行。 有沒有更好的方法來編寫這個,以便沒有DeadStore,但可讀?

   if (aqForm.getId() != null) {
        try {
            int i = Integer.parseInt(aqForm.getId());
            aqForm.setId(aqForm.getId().trim());
        } catch (NumberFormatException nfe) {
            result.rejectValue("id", "error.id", "Please enter an integer.");
            foundError = true;
        }
    }

只需調用方法並忽略結果,理想情況下使用注釋來解釋原因:

// Just validate
Integer.parseInt(aqForm.getId());

你為什么要修剪沒有驗證,而不是你擁有的版本的版本,你要知道這並不清楚。 我更喜歡:

String id = aqForm.getId();
if (id != null) {
    try {
        id = id.trim();
        // Validate the ID
        Integer.parseInt(id);
        // Store the "known good" value, post-trimming
        aqForm.setId(id);
    } catch (NumberFormatException nfe) {
        result.rejectValue("id", "error.id", "Please enter an integer.");
        foundError = true;
    }
}

你不必分配給i 你可以調用parseInt()並忽略結果:

   if (aqForm.getId() != null) {
        try {
            Integer.parseInt(aqForm.getId()); // validate by trying to parse
            aqForm.setId(aqForm.getId().trim());
        } catch (NumberFormatException nfe) {
            result.rejectValue("id", "error.id", "Please enter an integer.");
            foundError = true;
        }
    }

也就是說,我會創建一個輔助函數:

   public static boolean isValidInteger(String str) {
      ...
   }

並像這樣重寫你的代碼片段:

   String id = aqForm.getId();
   if (id != null) {
      if (isValidInteger(id)) {
         aqForm.setId(id.trim());
      } else {
         result.rejectValue("id", "error.id", "Please enter an integer.");
         foundError = true;
      }
   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM