欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 前端技术 > javascript >内容正文

javascript

FindBugs和JSR-305

发布时间:2023/12/3 javascript 51 豆豆
生活随笔 收集整理的这篇文章主要介绍了 FindBugs和JSR-305 小编觉得挺不错的,现在分享给大家,帮大家做个参考.
假设那组开发人员在大型项目的各个部分上并行工作–一些开发人员在进行服务实现,而其他开发人员在使用该服务的代码。 考虑到API的假设,两个小组都同意服务API,并开始单独工作。

您认为这个故事会有幸福的结局吗? 好吧,…–也许是:) –有一些工具可以帮助实现它:) –其中之一是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的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。