无效的Java
也許我可以被機器人代替進行代碼審查。 有一些反饋我發(fā)現(xiàn)自己一遍又一遍。 這是我最不喜歡的一些:
通用代碼結(jié)構(gòu)
放棄其他
if return的else就是多余的,并造成不必要的縮進。
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)測試代碼
之前是一個重型初始化器
我們使用@Before方法來設(shè)置復(fù)雜的對象,通常我們需要進行處理以計算類實例成員需要包含的對象。 另一方面,它是過大的:
// 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的一切
內(nèi)置的JUnit斷言不如AssertJ提供的斷言豐富。 至少,我建議使用某種形式的assertThat ,這樣您就不會最終使用對情況有點弱的斷言。
您的assertEquals是錯誤的方法
60%的時間,當(dāng)我使用assertEquals查看代碼時,順序是錯誤的。 提示:使用AssertJ !!! JUnit在這一點上是錯誤的! 我們應(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時報(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é)
- 上一篇: 银行备案表是什么(网银备案表)
- 下一篇: ddos的工作原理(ddos工作原理)