javascript
FindBugs和JSR-305
您認為這個故事會有幸福的結局嗎? 好吧,…–也許是:) –有一些工具可以幫助實現它:) –其中之一是FindBugs ,它受JSR-305(用于軟件缺陷檢測的注釋)支持。
讓我們看一下服務API合同:
package com.blogspot.vardlokkur.services;import java.util.List;import javax.annotation.CheckForNull; import javax.annotation.Nonnull;import com.blogspot.vardlokkur.entities.domain.Employer;/*** Defines the API contract for the employer service.** @author Warlock* @since 1.0*/ public interface EmployerService {/*** @param identifier the employer's identifier* @return the employer having specified {@code identifier}, {@code null} if not found*/@CheckForNull Employer withId(@Nonnull Long identifier);/*** @param specification defines which employers should be returned* @return the list of employers matching specification*/@Nonnull List thatAre(@Nonnull Specification specification);}如您所見,在服務方法簽名中添加了諸如@ Nonnull或@ CheckForNull之類的注釋。 使用它們的目的是定義方法參數的要求(例如, 標識符參數不能為null ),以及方法返回的值的期望值(例如,服務方法的結果可以為null ,應在代碼中檢查一下) )。
所以呢? –您可能會問–我應該自己檢查代碼還是讓同事相信他們會使用這些注釋定義的準則? 當然不是:) –不信任任何人,請使用可驗證API假設的工具,例如FindBugs 。
假設我們有以下服務API用法:
package com.blogspot.vardlokkur.test;import org.junit.Before; import org.junit.Test;import com.blogspot.vardlokkur.services.EmployerService; import com.blogspot.vardlokkur.services.impl.DefaultEmployerService;/*** Employer service test.** @author Warlock* @since 1.0*/ public class EmployerServiceTest {private EmployerService employers;@Beforepublic void before() {employers = new DefaultEmployerService();}@Testpublic void test01() {Long identifier = null;employers.withId(identifier);}@Testpublic void test02() {employers.withId(Long.valueOf(1L)).getBusinessName();}@Testpublic void test03() {employers.thatAre(null);} }讓我們嘗試根據服務API假設來??驗證代碼:
FindBugs將分析您的代碼,并切換到顯示潛在問題的FindBugs透視圖:
| 為null參數傳遞了null |
| 可能的空指針取消引用 |
類似地,例如,編寫服務代碼的人可以對照定義的API假設來??驗證其工作。 如果您為服務實現的早期版本運行FindBugs :
package com.blogspot.vardlokkur.services.impl;import java.util.List;import com.blogspot.vardlokkur.entities.domain.Employer; import com.blogspot.vardlokkur.services.EmployerService; import com.blogspot.vardlokkur.services.Specification;/*** Default implementation of {@link EmployerService}.** @author Warlock* @since 1.0*/ public class DefaultEmployerService implements EmployerService {/*** {@inheritDoc}*/public Employer withId(Long identifier) {return null;}/*** {@inheritDoc}*/public List thatAre(Specification specification) {return null;}}將發現以下錯誤:
如您所見,FindBugs和他的盟友-JSR-305沒有什么可以隱藏的;)
甜點的幾個鏈接:
- JSR-305:軟件缺陷檢測的批注
- JSR 305:一顆子彈還是根本沒有?
參考: JCG合作伙伴提供的 FindBugs和JSR-305 ? Micha? 術士思想博客上的Ja?tak。
翻譯自: https://www.javacodegeeks.com/2012/03/findbugs-and-jsr-305.html
總結
以上是生活随笔為你收集整理的FindBugs和JSR-305的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 文物局备案证明怎么弄的(文物局备案证明怎
- 下一篇: 房屋备案后能撤销吗(房屋备案后能撤销吗)