也许我可以被机器人代替进行代码审查。 有一些反馈我发现自己一遍又一遍。 这是我最不喜欢的一些:
通用代码结构
放弃其他
if
return
的else
就是多余的,并造成不必要的缩进。
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