无论是日常编码,还是业务涉及,能够优雅的表达思想,提高代码简洁度,阅读性都是一种能力,总结一下优雅的做法
优雅的关闭流
java7 try with resource,针对实现了AutoCloseable接口的类,都可优雅的关闭流,从而舍弃finally关闭
try catch finally
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| BufferedReader in = null; try { .... } catch (Exception e) { e.printStackTrace(); }finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } }
|
try winth resource
1 2 3 4 5 6 7
| try (final BufferedReader in = new BufferedReader(new InputStreamReader((new URL(url + "?" + param)).openConnection().getInputStream()));PrintWriter out =new PrintWriter(response.getWriter())){
... }catch{
}
|
Netty 优雅的关闭流程
Lambda表达式
list求交集
1
| List<Long> collect = list1.stream().filter(list2::contains).collect(Collectors.toList());
|
设计模式代替if else,策略模式,模板模式
代码整洁度,例如多注入service,按着高矮胖瘦排列,视觉舒适,controller求求你别写业务代码了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| public List getRandomList(List<?> paramList,int count){ if(count==0){ return null; } Random random=new Random(); List<Integer> tempList=new ArrayList<>(); List newList=new ArrayList(); int temp=0; if(count<=1){ temp = random.nextInt(paramList.size()); newList.add(paramList.get(temp)); }else { for(int i=0;i<Math.ceil(count);i++){ temp=random.nextInt(paramList.size()); if(!tempList.contains(temp)){ tempList.add(temp); newList.add(paramList.get(temp)); } else{ i--; } } } return newList; }
|
优雅判空
个人喜欢Assert判空,至于java8的Optional并没体会到优雅之处,日常StringUtils,Collections,isNoBlank等,
1 2 3 4 5 6 7
| public String testOptional(Test test) { return Optional.ofNullable(test).flatMap(Test::getTest3) .flatMap(Test3::getTest2) .map(Test2::getInfo) .orElse(""); } 看起来挺优雅,但日常没体会到
|
还有日常常用的instanceof
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| else if (f instanceof TreeBin) { validated = true; TreeBin<K,V> t = (TreeBin<K,V>)f; TreeNode<K,V> r, p; if ((r = t.root) != null && (p = r.findTreeNode(hash, key, null)) != null) { V pv = p.val; if (cv == null || cv == pv || (pv != null && cv.equals(pv))) { oldVal = pv; if (value != null) p.val = value; else if (t.removeTreeNode(p)) setTabAt(tab, i, untreeify(t.first)); } } }
|