首頁  >  文章  >  Java  >  java程式碼實例分析

java程式碼實例分析

PHPz
PHPz轉載
2023-05-10 11:58:061690瀏覽

一、幾個坑爹代碼的目錄

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 " +                      "<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>" +                      "");          }          sb.append("</root>");          System.out.println(sb.toString());      }  }

三、坑爹代碼 | 你寫過的最長的一行程式碼有多長? ? ?

java程式碼實例分析

你寫過的最長的一行程式碼有多長嗎?為什麼要寫這麼長?是看著帥呢,還是想減少程式碼行數?

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());</operationpurchaseinfo>

上面這段程式碼雖然被拆開多行顯示,但本質上是一行,一個極其複雜的賦值語句!

這種程式碼是不是為了讓別人看不懂來彰顯自己的編碼層次呢?

小編覺得 Java Stream API 以及各種函數式程式設計方法,以及各種語法糖在某種程度讓這種糟糕程式碼越來越多!

那麼一起來批判一下這個程式碼,或者你有什麼好的解決方案呢?

四、坑爹代碼 | 循環 條件判斷,你最多能嵌套幾層?

for 迴圈和 if 條件判斷語句,必不可少吧。但是你看過最多嵌套的循環和條件判斷有幾層呢?或者說,你最多能容忍多少層的嵌套呢?

java程式碼實例分析

我們還是先來看看極端的坑爹代碼吧:

// 这个***循环嵌套,只是总循环的一部分。。。我已经绕晕在黄桷湾立交          if (recordList.size() > start) {              for (int i = start; i  map = recordList.get(i);                  Map<string> field11 = (Map<string>) map.get("field"); //name -> code                  Map<string> record11 = (Map<string>) map.get("record"); // code -> value                  String 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>> salaryDataVos = page3.getRecords();                      salaryDataVos = this.reSetMap(salaryDataVos, null, null);                      for (Map<string> map2 : salaryDataVos) {                          Map<string> field2 = (Map<string>) map2.get("field");                          Map<string> record2 = (Map<string>) 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> 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);              }          }</salarygroupvo></string></salarygroupvo></string></string></string></string></string></map></string></string></string></string>

五、坑爹代碼| 為了後期優化查詢速度~ 頗有商業頭腦!

什麼樣的程式設計師是個好程式設計師呢?當我們在為客戶開發系統時候,為了後期的最佳化,預留一些埋點。

透過對這些埋點的優化,可以讓客戶瞬間感覺系統在運行速度上有質的飛躍,讓公司順利的簽署二期開發合同,收取巨額開發費用。

從公司角度來看,這樣的程式設計師就是一個好程式設計師。 

例如:

java程式碼實例分析

六、坑爹代碼 | 你是如何被異常玩然後變成玩異常的?

玩 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程式碼實例分析

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程式碼實例分析的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除