史上最坑爹的代码!个个让人崩溃!
本文整理自:開源中國 | 碼云
Java 就是這么一門神奇的語言,任何水平的人都能寫出可以運行的代碼,但是一看代碼便知水平高低。作為一個程序員,你看過哪些坑爹代碼,你又寫過多少坑爹代碼,還有多少你不知道的坑爹代碼?
有意思的是碼云上建了一個代碼倉庫:bullshit-codes,倉庫的目的就是為了收集這些坑爹代碼,可以讓別人不掉坑或者少掉坑,可以避免自己掉坑,或許哈哈一樂!
上邊匯聚了各種編程語言的,倉庫地址如下:
https://gitee.com/oschina/bullshit-codes
本文小編給大家整理了幾個比較坑爹的代碼,整理了幾個之后,實在整理不下去了,僅供大家參考,看看能不能崩潰掉!
一、幾個坑爹代碼的目錄
1、這樣使用 StringBuffer 的方法有什么坑?
2、你寫過的最長的一行代碼有多長???
3、循環+條件判斷,你最多能嵌套幾層?
4、為了后期優化查詢速度 ~ 頗有商業頭腦!
5、你是如何被異常玩然后變成玩異常的?
6、Stream 玩得最 6 的代碼,看過的人都驚呆了!
二、坑爹代碼 |?這樣使用 StringBuffer 的方法有什么坑?
你是否曾經這樣使用過 Java 的 StringBuffer 類?
/*** Create Time 2019/5/24* StringBuffer追加 如癡如醉的寫法* @author cailong**/ public class Append {public static void main(String[] ares){StringBuffer sb = new StringBuffer();//這里都能理解sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><ROOT>");for (int i = 0; i < 10; i++) {//為什么到這里就要這樣寫???既然都用StringBuffer了 (這里省略集合遍歷用i代替 意思能懂就行)sb.append("<NSRXX>" +"<NSRSBH>"+i+"</NSRSBH>" +"<NSRMC>"+i+"</NSRMC>" +"<DJXH>"+i+"</DJXH>" +"<ZGSWJ_DM>"+i+"</ZGSWJ_DM>" +"<ZGSWJ_MC>"+i+"</ZGSWJ_MC>" +"<SJLY>sjzs</SJLY>" +"<YWSX_DM>"+i+"</YWSX_DM>" +"</NSRXX>");}sb.append("</ROOT>");System.out.println(sb.toString());} }三、坑爹代碼 |?你寫過的最長的一行代碼有多長???
你寫過的最長的一行代碼有多長嗎?你為什么要寫這么長?是看著帥呢,還是想減少代碼行數?
List<OperationPurchaseInfo> purchaseInfoList= sheet.getPurchaseInfoList().stream().filter(purchaseInfo -> purchaseInfo.getExteriorOperation().getExteriorPart().getExteriorOperationList().stream().filter(exteriorOperation -> exteriorOperation.getProcessState().equals(ExteriorOperation.ProcessState.PROCESSING)).count() != 0// 訂單明細中工序對應的工件下的其他工序存在加工中,// 且已發給供應商且供應商不是當前訂單供應商時,需要判斷&& (purchaseInfo.getExteriorOperation().getExteriorPart().getTeamwork() == null || !purchaseInfo.getExteriorOperation().getExteriorPart().getTeamwork().equals(sheet.getTeamwork()))).collect(Collectors.toList());上面這段代碼雖然被拆開多行顯示,但本質上是一行,一個極其復雜的賦值語句!
這種代碼是不是為了讓別人看不懂來彰顯自己的編碼水平呢?
小編覺得 Java Stream API 以及各種函數式編程方法,以及各種語法糖在某種程度讓這種糟糕代碼越來越多!
那么一起來批判一下這個代碼,或者你有什么好的解決方案呢?
四、坑爹代碼 |?循環+條件判斷,你最多能嵌套幾層?
for 循環和 if 條件判斷語句,必不可少吧。但是你見過最多嵌套的循環和條件判斷有幾層呢?或者說,你最多能容忍多少層的嵌套呢?
我們還是先來看看極端的坑爹代碼吧:
// 這個無限循環嵌套,只是總循環的一部分。。。我已經繞暈在黃桷灣立交if (recordList.size() > start) {for (int i = start; i < end; i++) {Map<String, Object> map = recordList.get(i);Map<String, Object> field11 = (Map<String, Object>) map.get("field"); //name -> codeMap<String, Object> record11 = (Map<String, Object>) map.get("record"); // code -> valueString catagory1 = map.get("categoryId").toString();// 查詢第一種類型對應的其他類型SalaryDataVo ss = JSON.parseObject(JSON.toJSONString(map), SalaryDataVo.class);Page page3 = salaryManagerService.getAllRecordsByCondition(ss);if (page3.getRecords().size() > 0) {List<Map<String, Object>> salaryDataVos = page3.getRecords();salaryDataVos = this.reSetMap(salaryDataVos, null, null);for (Map<String, Object> map2 : salaryDataVos) {Map<String, Object> field2 = (Map<String, Object>) map2.get("field");Map<String, Object> record2 = (Map<String, Object>) map2.get("record");String catagory2 = map2.get("categoryId").toString();List<SalaryGroupVO> groupList2 = salaryGroupService.getSalaryGroupsItems(this.getUserCorpId(), catagory2);for (SalaryGroupVO cc : groupList2) {cc.setCode(cc.getParentId() + cc.getCode());}//計算for (Map.Entry<String, Object> entity : field2.entrySet()) {String keyName = entity.getKey();for (SalaryGroupVO s2 : groupList2) {if ("bigDecimal".equals(s2.getItemType()) && s2.getCode().equals(field2.get(keyName).toString()) && ("部門" != keyName) && ("姓名" != keyName) && StringUtils.isNotEmpty(s2.getItemType())) {if (field11.containsKey(keyName)) {if (field11.containsKey(keyName)) {String code1 = field11.get(keyName).toString();Double newValue = 0.0;Double oldValue = 0.0;if (!record11.get(code1).toString().matches("^[0-9]*$")) {oldValue = Double.parseDouble(record11.get(code1).toString());if (record2.containsKey(entity.getValue().toString()) && (!record2.get(entity.getValue().toString()).toString().matches("^[0-9]*$"))) {String value2 = record2.get(entity.getValue().toString()).toString();newValue = Double.parseDouble(value2);}record11.remove(field11.get(keyName).toString());}if (code1.startsWith(catagory1) || code1.startsWith(catagory2)) {String co = code1.replace(catagory1, "hz");field11.put(keyName, co);record11.put(co, oldValue + newValue);}}} else {String code = entity.getValue().toString();String str = entity.getValue().toString();Object value2 = record2.get(entity.getValue().toString());if (str.startsWith(catagory1) && str.replace(catagory1, "").startsWith("hz")) {code = str.replace(catagory1, "");} else if (str.startsWith(catagory2) && str.replace(catagory2, "").startsWith("hz")) {code = str.replace(catagory2, "");}field11.put(keyName, code);record11.put(code, value2);}}}}}}List<SalaryGroupVO> sList = salaryGroupService.getSalaryGroupItemsByParentId(catagory1);for (SalaryGroupVO s : sList) {if (field11.containsKey(s.getName()) && s.getCode().startsWith("hz")) {String k = field11.get(s.getName()).toString();field11.put(s.getName(), s.getCode());String value = null;if (record11.containsKey(k)) {value = record11.get(k).toString();}record11.put(s.getCode(), value);}}resultList.add(map);pageInfo.setRecords(resultList);}}我數了數,一共有 11 層的嵌套!!!
吐槽歸吐槽,這樣的代碼邏輯有什么重構的好方法嗎?
五、坑爹代碼 |?為了后期優化查詢速度 ~ 頗有商業頭腦!
什么樣的程序員是一個好程序員呢?當我們在給客戶開發系統時候,為了后期的優化,預留一些埋點。
通過對這些埋點的優化,可以讓客戶瞬間感覺系統在運行速度上有質的飛躍,讓公司順利的簽署二期開發合同,收取巨額開發費用。
從公司角度來看,這樣的程序員就是一個好程序員。 —— 這句話不是紅薯說的!
比如:
我想說的是:兇碟,你下手能否不那么狠啊,建議對代碼進行優化,改成?Thread.sleep(1000);??—— 這句話也不是紅薯說的。
或者你有什么更好的建議呢?不要覺得駭人聽聞,真有這樣的人,這樣的代碼!!!
六、坑爹代碼 |?你是如何被異常玩然后變成玩異常的?
玩 Java 的人,剛開始會被各種異常虐,空指針應該是最常見的。多玩兩年就開始玩異常,各種奇葩異常玩法層出不窮。
你覺得下面這種異常的定義妥嗎?
/*** 處理業務的異常* 居然有一堆靜態異常,準備好了隨時可以拋??* 錯誤碼是字符串*/ public class CommandException extends BaseException {private static final long serialVersionUID = -6354513454371927970L;public static CommandException PARAM_NULL= new CommandException("Command_assemble_01", "Parameter is Needed But Empty");public static CommandException DEVID_NULL = new CommandException("Command_assemble_02", "DevId Cannot Be Null");public static CommandException MDCODE_NULL = new CommandException("Command_assemble_03", "Model Code Cannot Be Empty");public static CommandException ORDER_NULL = new CommandException("Command_assemble_04", "Order Cannot Be Empty");public static CommandException TYPE_NULL = new CommandException("Command_assemble_05", "Upstream / Downstream Type Cannot Be Empty");public static CommandException MENUID_NULL = new CommandException("Command_assemble_06", "Menu Id Cannot Be Null");public static CommandException CTRLTYPE_NOT_RANGE= new CommandException("Command_assemble_07", "Ctrltype Cannot Be Recognized, Which is not in Range");public static CommandException CMD_NULL = new CommandException("Command_analyze_01", "CMD Cannot Be Null");public static CommandException PAYLOAD_NULL = new CommandException("Command_analyze_02", "Payload Cannot Be Null");public static CommandException FRAMEWORK_FAILED= new CommandException("Command_analyze_03", "Framework Failed to be Checked");public static CommandException CHECK_FAILED= new CommandException("Command_analyze_04", "Command Failed to be Checked");public static CommandException CONFIGURE_NOT_EXIST = new CommandException("Command_error_1001", "Configure is not Exist");public static CommandException REDIS_ERROR = new CommandException("Command_error_1002", "Cache Command in Redis Error", true);//省略構造函數、get/set方法 }如果不妥,有什么問題呢??
七、坑爹代碼 |?Stream 玩得最 6 的代碼,看過的人都驚呆了!
Stream 作為 Java 8 的一大亮點,它與 java.io 包里的 InputStream 和 OutputStream 是完全不同的概念。Java 8 中的 Stream 是對集合(Collection)對象功能的增強,它專注于對集合對象進行各種非常便利、高效的聚合操作(aggregate operation),或者大批量數據操作 (bulk data operation)。Stream API 借助于同樣新出現的 Lambda 表達式,極大的提高編程效率和程序可讀性。
那么 Java 8 的 Stream 到底是王者,還是個巨坑,這完全取決于你是怎么玩的?
我不得不說,下面代碼是我從業 20 年(說誰呢,誰從業 20 年,我今年 19? 歲!!!)看過最牛逼的 Stream 的用法:
//Stream 用的66的 final EventAction eventAction = redisObj(EventActionKey + distributionEventId,() -> Optional.of(distributionEventId).map(eventId -> {final EventActionExample example = new EventActionExample();example.createCriteria().andEventIdEqualTo(eventId).andTriggerTypeEqualTo(EnumEventTriggerType.DISTRIBUTION_PURCHASE.getCode().byteValue());return example;}).map(eventActionMapper::selectByExample).filter(StringUtil::isNotEmpty).map(e -> e.get(0)).orElseThrow(() -> ExceptionUtil.createParamException("事件觸發信息不存在")), EventAction.class);final AwardConfig awardConfig = redisObj(EventConfigKey + eventAction.getId(),() -> Optional.ofNullable(eventAction.getId()).map(actionId -> {final AwardConfigExample example = new AwardConfigExample();example.createCriteria().andActionIdEqualTo(actionId);return example;}).map(awardConfigMapper::selectByExample).filter(StringUtil::isNotEmpty).map(e -> e.get(0)).orElseThrow(() -> ExceptionUtil.createParamException("xxx")),AwardConfig.class);Optional.of(req).map(e -> e.clueUid).map(id -> {final ClueExample example = new ClueExample();example.createCriteria().andClueUidEqualTo(id).andDeletedEqualTo(false).andReceivedEqualTo(false).andCreateTimeGreaterThan(now - cluetime);example.setOrderByClause("create_time asc");return example;}) // 獲取該被邀請人所有未過期且未被領取的線索的線索.map(clueMapper::selectByExample).filter(StringUtil::isNotEmpty).ifPresent(clues -> {final ClueResp clueResp = Optional.of(req).filter(c -> {c.count = clues.size();return true;}).map(this::awardValue).orElseThrow(() -> ExceptionUtil.createParamException("參數錯誤"));final Integer specialId = req.getIsHead()? clues.get(0).getId(): clues.get(clues.size() - 1).getId();clues.stream().peek(clue -> {final AwardConfig awardConfigclone = Optional.of(awardConfig).map(JSONUtil::obj2Json).map(json -> JSONUtil.json2Obj(json, AwardConfig.class)).orElseGet(AwardConfig::new);awardConfigclone.setMoney(Optional.of(clue.getId()).filter(specialId::equals).map(e -> clueResp.specialReward.longValue()).orElse(clueResp.otherAverageReward.longValue()));eventActionService.assembleAward(awardConfigclone,clue.getAdviserUid(),clue.getAdviserUid(),clue.getClueUid(),eventAction,new PasMessageParam(),clue.getId(),AwardRelationType.Clud.code());}).forEach(clue -> {clue.setOrderNo(req.orderNo);clue.setCommodityName(req.commodityName);clue.setOrderAmount(req.orderAmount);clue.setReceived(true);clue.setModifyTime(now);clueMapper.updateByPrimaryKeySelective(clue);});});?
Java 就是這么一門神奇的語言,任何水平的人都能寫出可以運行的代碼,但是一看代碼便知水平高低。但是這樣的 Stream 代碼你一定一口老談不吐不快!
八、小編已陣亡
好了,小編實在整理不下去了,大家有興趣的可以去:
https://gitee.com/oschina/bullshit-codes
更進一步的吐槽!
總結
以上是生活随笔為你收集整理的史上最坑爹的代码!个个让人崩溃!的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 我的天!史上最烂的项目:苦撑12年,60
- 下一篇: 原创 | 我被面试官给虐懵了,竟然是因为