您认为这个故事会有幸福的结局吗? 好吧,…–也许是:) –有一些工具可以帮助实现它:) –其中之一是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;
@Before
public void before() {
employers = new DefaultEmployerService();
}
@Test
public void test01() {
Long identifier = null;
employers.withId(identifier);
}
@Test
public void test02() {
employers.withId(Long.valueOf(1L)).getBusinessName();
}
@Test
public 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没有什么可以隐藏的;)
甜点的几个链接:
参考: JCG合作伙伴提供的 FindBugs和JSR-305 Micha? 术士思想博客上的Ja?tak。
翻译自: https://www.javacodegeeks.com/2012/03/findbugs-and-jsr-305.html