无效的Java
也許我可以被機(jī)器人代替進(jìn)行代碼審查。 有一些反饋我發(fā)現(xiàn)自己一遍又一遍。 這是我最不喜歡的一些:
通用代碼結(jié)構(gòu)
放棄其他
if return的else就是多余的,并造成不必要的縮進(jìn)。
if (foo) { return bar; } else { return baz; } // should be replaced by if (foo) { return bar; } return baz;數(shù)組->列表->流
List< ... > list = Arrays.asList(someArray); list.stream(...) // should be replaced by Arrays.stream(someArray)測(cè)試代碼
之前是一個(gè)重型初始化器
我們使用@Before方法來(lái)設(shè)置復(fù)雜的對(duì)象,通常我們需要進(jìn)行處理以計(jì)算類實(shí)例成員需要包含的對(duì)象。 另一方面,它是過(guò)大的:
// 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 );測(cè)試投擲
@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的一切
內(nèi)置的JUnit斷言不如AssertJ提供的斷言豐富。 至少,我建議使用某種形式的assertThat ,這樣您就不會(huì)最終使用對(duì)情況有點(diǎn)弱的斷言。
您的assertEquals是錯(cuò)誤的方法
60%的時(shí)間,當(dāng)我使用assertEquals查看代碼時(shí),順序是錯(cuò)誤的。 提示:使用AssertJ !!! JUnit在這一點(diǎn)上是錯(cuò)誤的! 我們應(yīng)該從左到右閱讀。
// wrong: assertEquals(something.getFoo(), 123 ); // it's expected IS actual assertEquals( 123 , something.getFoo());Mockito靜態(tài)導(dǎo)入
// this is not normal Mockito.verify(mock).called(); // static import all mockito methods verify(mock).called();Mockito時(shí)報(bào)(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
總結(jié)
- 上一篇: 银行备案表是什么(网银备案表)
- 下一篇: modbus调试时间超时_Java调试器