无效的Java

也许我可以被机器人代替进行代码审查。 有一些反馈我发现自己一遍又一遍。 这是我最不喜欢的一些:

通用代码结构

放弃其他

if returnelse就是多余的,并造成不必要的缩进。

 if (foo) { 
    return bar;  } else { 
    return baz;  }  // should be replaced by  if (foo) { 
    return bar;  }  return baz; 

数组->列表->流

 List< ... > list = Arrays.asList(someArray);  list.stream(...)  // should be replaced by  Arrays.stream(someArray) 

测试代码

之前是一个重型初始化器

我们使用@Before方法来设置复杂的对象,通常我们需要进行处理以计算类实例成员需要包含的对象。 另一方面,它是过大的:

 // this is part 1 of two  private MyService myService;  @Before  public void before() { 
     // now initialize 
     myService = new MyService().init( 123 );  }  // the above code can be expressed in the initializer  // and is simple to read there...  // if it threw exceptions or needed some more complex  // set up, it wouldn't be  // it's in one clear place where we know where to  // find it  private MyService myService = new MyService() 
     .init( 123 ); 

测试投掷

 @Test  public void someTest() 
     throws IOException, JsonException {  }  // never bother with multiple or specific exception  // throws in tests nobody cares and it's just noise  // the test runner will catch anything!  @Test  public void someTest() throws Exception {  } 

断言大小

 // long-winded  assertThat(list.size()).isEqualTo(2);  // should be  assertThat(list).hasSize(2); 

AssertJ的一切

内置的JUnit断言不如AssertJ提供的断言丰富。 至少,我建议使用某种形式的assertThat ,这样您就不会最终使用对情况有点弱的断言。

您的assertEquals是错误的方法

60%的时间,当我使用assertEquals查看代码时,顺序是错误的。 提示:使用AssertJ !!! JUnit在这一点上是错误的! 我们应该从左到右阅读。

 // wrong:  assertEquals(something.getFoo(), 123 );  // it's expected IS actual  assertEquals( 123 , something.getFoo()); 

Mockito静态导入

 // this is not normal  Mockito.verify(mock).called();  // static import all mockito methods  verify(mock).called(); 

Mockito时报(1)

 // this is a tautology  verify(mock, times( 1 )).called();  // look at what verify(mock) does internally  // replace with  verify(mock).called(); 

翻译自: https://www.javacodegeeks.com/2019/10/ineffective-java.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值