您好,登錄后才能下訂單哦!
這篇文章主要介紹“java代碼實(shí)例分析”的相關(guān)知識(shí),小編通過(guò)實(shí)際案例向大家展示操作過(guò)程,操作方法簡(jiǎn)單快捷,實(shí)用性強(qiáng),希望這篇“java代碼實(shí)例分析”文章能幫助大家解決問(wèn)題。
一、幾個(gè)坑爹代碼的目錄
1、這樣使用 StringBuffer 的方法有什么坑?
2、你寫(xiě)過(guò)的最長(zhǎng)的一行代碼有多長(zhǎng)???
3、循環(huán)+條件判斷,你最多能嵌套幾層?
4、為了后期優(yōu)化查詢(xún)速度 ~ 頗有商業(yè)頭腦!
5、你是如何被異常玩然后變成玩異常的?
6、Stream 玩得最 6 的代碼,看過(guò)的人都驚呆了!
二、坑爹代碼 | 這樣使用 StringBuffer 的方法有什么坑?
你是否曾經(jīng)這樣使用過(guò) Java 的 StringBuffer 類(lèi)?
/** * Create Time 2019/5/24 * StringBuffer追加 如癡如醉的寫(xiě)法 * @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++) { //為什么到這里就要這樣寫(xiě)???既然都用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()); } }
三、坑爹代碼 | 你寫(xiě)過(guò)的最長(zhǎng)的一行代碼有多長(zhǎng)???
你寫(xiě)過(guò)的最長(zhǎng)的一行代碼有多長(zhǎng)嗎?你為什么要寫(xiě)這么長(zhǎng)?是看著帥呢,還是想減少代碼行數(shù)?
List<OperationPurchaseInfo> purchaseInfoList = sheet.getPurchaseInfoList() .stream() .filter(purchaseInfo -> purchaseInfo.getExteriorOperation() .getExteriorPart() .getExteriorOperationList() .stream() .filter(exteriorOperation -> exteriorOperation .getProcessState() .equals(ExteriorOperation.ProcessState.PROCESSING)) .count() != 0 // 訂單明細(xì)中工序?qū)?yīng)的工件下的其他工序存在加工中, // 且已發(fā)給供應(yīng)商且供應(yīng)商不是當(dāng)前訂單供應(yīng)商時(shí),需要判斷 && (purchaseInfo.getExteriorOperation() .getExteriorPart() .getTeamwork() == null || !purchaseInfo.getExteriorOperation() .getExteriorPart().getTeamwork().equals(sheet.getTeamwork())) ).collect(Collectors.toList());
上面這段代碼雖然被拆開(kāi)多行顯示,但本質(zhì)上是一行,一個(gè)極其復(fù)雜的賦值語(yǔ)句!
這種代碼是不是為了讓別人看不懂來(lái)彰顯自己的編碼水平呢?
小編覺(jué)得 Java Stream API 以及各種函數(shù)式編程方法,以及各種語(yǔ)法糖在某種程度讓這種糟糕代碼越來(lái)越多!
那么一起來(lái)批判一下這個(gè)代碼,或者你有什么好的解決方案呢?
四、坑爹代碼 | 循環(huán)+條件判斷,你最多能嵌套幾層?
for 循環(huán)和 if 條件判斷語(yǔ)句,必不可少吧。但是你見(jiàn)過(guò)最多嵌套的循環(huán)和條件判斷有幾層呢?或者說(shuō),你最多能容忍多少層的嵌套呢?
我們還是先來(lái)看看極端的坑爹代碼吧:
// 這個(gè)***循環(huán)嵌套,只是總循環(huán)的一部分。。。我已經(jīng)繞暈在黃桷灣立交 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 -> code Map<String, Object> record11 = (Map<String, Object>) map.get("record"); // code -> value String catagory1 = map.get("categoryId").toString(); // 查詢(xún)***種類(lèi)型對(duì)應(yīng)的其他類(lèi)型 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()); } //計(jì)算 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()) && ("部門(mén)" != 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); } }
五、坑爹代碼 | 為了后期優(yōu)化查詢(xún)速度 ~ 頗有商業(yè)頭腦!
什么樣的程序員是一個(gè)好程序員呢?當(dāng)我們?cè)诮o客戶(hù)開(kāi)發(fā)系統(tǒng)時(shí)候,為了后期的優(yōu)化,預(yù)留一些埋點(diǎn)。
通過(guò)對(duì)這些埋點(diǎn)的優(yōu)化,可以讓客戶(hù)瞬間感覺(jué)系統(tǒng)在運(yùn)行速度上有質(zhì)的飛躍,讓公司順利的簽署二期開(kāi)發(fā)合同,收取巨額開(kāi)發(fā)費(fèi)用。
從公司角度來(lái)看,這樣的程序員就是一個(gè)好程序員。
比如:
六、坑爹代碼 | 你是如何被異常玩然后變成玩異常的?
玩 Java 的人,剛開(kāi)始會(huì)被各種異常虐,空指針應(yīng)該是最常見(jiàn)的。多玩兩年就開(kāi)始玩異常,各種奇葩異常玩法層出不窮。
你覺(jué)得下面這種異常的定義妥嗎?
/** * 處理業(yè)務(wù)的異常 * 居然有一堆靜態(tài)異常,準(zhǔn)備好了隨時(shí)可以?huà)???nbsp; * 錯(cuò)誤碼是字符串 */ 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); //省略構(gòu)造函數(shù)、get/set方法 }
如果不妥,有什么問(wèn)題呢?
七、坑爹代碼 | Stream 玩得最 6 的代碼,看過(guò)的人都驚呆了!
Stream 作為 Java 8 的一大亮點(diǎn),它與 java.io 包里的 InputStream 和 OutputStream 是完全不同的概念。Java 8 中的 Stream 是對(duì)集合(Collection)對(duì)象功能的增強(qiáng),它專(zhuān)注于對(duì)集合對(duì)象進(jìn)行各種非常便利、高效的聚合操作(aggregate operation),或者大批量數(shù)據(jù)操作 (bulk data operation)。Stream API 借助于同樣新出現(xiàn)的 Lambda 表達(dá)式,極大的提高編程效率和程序可讀性。
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("事件觸發(fā)信息不存在")) , 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; }) // 獲取該被邀請(qǐng)人所有未過(guò)期且未被領(lǐng)取的線(xiàn)索的線(xiàn)索 .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("參數(shù)錯(cuò)誤")); 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); }); } );
關(guān)于“java代碼實(shí)例分析”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí),可以關(guān)注億速云行業(yè)資訊頻道,小編每天都會(huì)為大家更新不同的知識(shí)點(diǎn)。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。